Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

accept Buffer as image input #372

Merged
merged 1 commit into from Feb 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions Source/dom/models/ImageData.js
@@ -1,4 +1,5 @@
import { isNativeObject } from 'util'
import { Buffer } from 'buffer'
import { DefinedPropertiesKey, WrappedObject } from '../WrappedObject'
import { Types } from '../enums'
import { Factory } from '../Factory'
Expand All @@ -10,6 +11,7 @@ import { isWrappedObject } from '../utils'
export class ImageData extends WrappedObject {
/**
* can accept a wide range of input:
* - a Buffer
* - a wrapped ImageData
* - a native NSImage
* - a native NSURL
Expand All @@ -25,17 +27,18 @@ export class ImageData extends WrappedObject {

let nsImage
if (isNativeObject(image)) {
const className = String(image.class())
if (className === 'NSImage') {
if (image.isKindOfClass(NSImage)) {
nsImage = image
} else if (className === 'NSData') {
} else if (image.isKindOfClass(NSData)) {
nsImage = NSImage.alloc().initWithData(image)
} else if (className === 'NSURL') {
} else if (image.isKindOfClass(NSURL)) {
nsImage = NSImage.alloc().initWithContentsOfURL(image)
} else if (className === 'MSImageData') {
} else if (image.isKindOfClass(MSImageData)) {
return ImageData.fromNative(image)
} else {
throw new Error(`Cannot create an image from a ${className}`)
throw new Error(
`Cannot create an image from a ${String(image.class())}`
)
}
} else if (typeof image === 'string' || (image && image.path)) {
nsImage = NSImage.alloc().initByReferencingFile(image.path || image)
Expand All @@ -49,8 +52,10 @@ export class ImageData extends WrappedObject {
} catch (err) {
throw new Error(err)
}
} else if (Buffer.isBuffer(image)) {
nsImage = NSImage.alloc().initWithData(image.toNSData())
} else {
throw new Error('`image` needs to be a string')
throw new Error('`image` needs to be a Buffer')
}

return ImageData.fromNative(MSImageData.alloc().initWithImage(nsImage))
Expand Down
1 change: 1 addition & 0 deletions docs/api/Image.md
Expand Up @@ -39,6 +39,7 @@ var imageLayer = new Image({
The image property accept a wide range of input:

- an [`ImageData`](#imagedata)
- a `Buffer`
- a native `NSImage`
- a native `NSURL`
- a native `MSImageData`
Expand Down