Skip to content

Commit

Permalink
make sure all raw pixel buffers are converted to 4 channels...
Browse files Browse the repository at this point in the history
because encoders expect images to have 4 channels.
  • Loading branch information
EyalAr committed Oct 2, 2015
1 parent 2a60f34 commit 1138482
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
6 changes: 3 additions & 3 deletions lib/obtain.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@
});
});
} else if (source instanceof Buffer) {
if(typeof type === 'object') {
if (typeof type === 'object') {
// it's a raw pixels buffer
var channelSize = type.width * type.height;
var numChannels = source.length / channelSize;
if (numChannels !== parseInt(numChannels) || numChannels < 1 || numChannels > 4) {
if (numChannels !== parseInt(numChannels) || numChannels < 1 || numChannels > 4)
throw Error("Buffer size does not match width and height");
}
if (numChannels !== 4) source = util.makeRgbaBuffer(source, numChannels);
callback(null, new Image(source, type.width, type.height, (numChannels % 2 === 0)));
} else if (typeof type === 'string') {
// it's an encoded image
Expand Down
31 changes: 30 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,42 @@
return 256;
}

function makeRgbaBuffer(orig, channels){
var chanLen = orig.length / channels;
if (chanLen !== parseInt(chanLen) || channels < 1 || channels > 3)
throw Error("Incorrect number of channels in original buffer");
var rgba = new Buffer(chanLen * 4);
switch (channels){
case 1:
orig.copy(rgba, 0, 0, chanLen);
orig.copy(rgba, chanLen, 0, chanLen);
orig.copy(rgba, 2 * chanLen, 0, chanLen);
rgba.fill(100, 3 * chanLen);
break;
case 2:
orig.copy(rgba, 0, 0, chanLen);
orig.copy(rgba, chanLen, 0, chanLen);
orig.copy(rgba, 2 * chanLen, 0, chanLen);
orig.copy(rgba, 3 * chanLen, chanLen);
break;
case 3:
orig.copy(rgba, 0, 0, chanLen);
orig.copy(rgba, chanLen, chanLen, 2 * chanLen);
orig.copy(rgba, 2 * chanLen, 2 * chanLen);
rgba.fill(100, 3 * chanLen);
break;
}
return rgba;
}

module.exports = {
undefinedFilter: undefinedFilter,
normalizeColor: normalizeColor,
normalizePngParams: normalizePngParams,
normalizeGifParams: normalizeGifParams,
normalizeJpegParams: normalizeJpegParams,
getClosest2Exp: getClosest2Exp
getClosest2Exp: getClosest2Exp,
makeRgbaBuffer: makeRgbaBuffer
};

})(void 0);

0 comments on commit 1138482

Please sign in to comment.