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

Fix crash when image data is invalid or in an unrecognized format #7

Merged
merged 1 commit into from
Jun 15, 2016
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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