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

Detect image type from buffer #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/obtain.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@
callback(null, new Image(source, type.width, type.height, (numChannels % 2 === 0)));
} else if (typeof type === 'string') {
// it's an encoded image
opener = getOpener(type);
opener(source, function(err, pixelsBuf, width, height, channels, trans) {
callback(err, err ? null : new Image(pixelsBuf, width, height, trans));
});
} else if (!type) {
//No type passed, auto resolve type from buffer
var resolvedType = require('file-type')(source);

//Faulty buffers or unresolved types will return null.
if (resolvedType === null) throw Error('Failed to auto resolve buffer type.');

type = resolvedType.ext;

opener = getOpener(type);
opener(source, function(err, pixelsBuf, width, height, channels, trans) {
callback(err, err ? null : new Image(pixelsBuf, width, height, trans));
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"dependencies": {
"async": "~0.9.0",
"decree": "0.0.6",
"nan": "~1.4.1"
"nan": "~1.4.1",
"file-type": "~2.0.1"
},
"scripts": {
"install": "node-gyp rebuild",
Expand Down
15 changes: 13 additions & 2 deletions tests/00.argsValidation/001.open.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ describe('lwip.open arguments validation', function() {
});

describe('without type', function() {
it('should throw an error', function() {
lwip.open.bind(lwip, buffer, function() {}).should.throwError();
it('should succeed', function() {
lwip.open.bind(lwip, buffer, function() {}).should.not.throw();
});
});
describe('with invalid type', function() {
Expand All @@ -69,6 +69,17 @@ describe('lwip.open arguments validation', function() {
});

});

describe('invalid buffer', function() {

var buffer = new Buffer("I'm not an image at all!", "utf-8");

describe('without type', function() {
it('should throw an error', function() {
lwip.open.bind(lwip, buffer, function() {}).should.throw(/Failed to auto resolve buffer type/);
});
});
});

describe('pixelbuffer', function() {

Expand Down