Skip to content

Commit

Permalink
Merge pull request #7 from teohhanhui/master
Browse files Browse the repository at this point in the history
Fix crash when image data is invalid or in an unrecognized format
  • Loading branch information
teohhanhui authored Jun 15, 2016
2 parents 557a7f6 + fe8a5cb commit 2805bc9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 8 additions & 3 deletions src/image.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use strict';

var _, Logger, env, modifiers, stream, util, imgType;
var _, Logger, env, modifiers, stream, util, imageType;

_ = require('lodash');
Logger = require('./utils/logger');
env = require('./config/environment_vars');
modifiers = require('./lib/modifiers');
stream = require('stream');
util = require('util');
imgType = require('image-type');
imageType = require('image-type');


// Simple stream to represent an error at an early stage, for instance a
Expand Down Expand Up @@ -188,10 +188,15 @@ Object.defineProperty(Image.prototype, 'format', {
Object.defineProperty(Image.prototype, 'contents', {
get: function () { return this._contents; },
set: function (data) {
var imgType;

this._contents = data;

if (this.isBuffer()) {
this.format = imgType(data).ext;
imgType = imageType(data);
if (imgType) {
this.format = imgType.ext;
}
this.isFormatValid();
}
}
Expand Down
10 changes: 9 additions & 1 deletion test/src/image-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,22 @@ describe('Image class', function(){
});

describe('#content', function () {
it ('should set the format based on the image data', function () {
it('should set the format based on the image data', function () {
var imgSrc = path.resolve(__dirname, '../sample_images/image1.jpg');
var buf = fs.readFileSync(imgSrc);
var img = new Img({path: '/path/to/image.jpg'});

img.contents = buf;
img.format.should.equal('jpeg');
});

it('should not die on invalid image data', function () {
var buf = new Buffer(5);
var img = new Img({path: '/path/to/image.jpg'});

img.contents = buf;
expect(img.format).to.not.exist;
});
});

describe('#parseImage', function(){
Expand Down

0 comments on commit 2805bc9

Please sign in to comment.