diff --git a/lib/obtain.js b/lib/obtain.js index 23999c9c..5cfba7b4 100644 --- a/lib/obtain.js +++ b/lib/obtain.js @@ -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)); diff --git a/package.json b/package.json index d5daf845..9fbc7a58 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/tests/00.argsValidation/001.open.js b/tests/00.argsValidation/001.open.js index c0bd291e..9d45d65e 100644 --- a/tests/00.argsValidation/001.open.js +++ b/tests/00.argsValidation/001.open.js @@ -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() { @@ -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() {