Skip to content

Instantly share code, notes, and snippets.

@wemakeweb
Last active December 14, 2015 05:49
Show Gist options
  • Select an option

  • Save wemakeweb/5038120 to your computer and use it in GitHub Desktop.

Select an option

Save wemakeweb/5038120 to your computer and use it in GitHub Desktop.
node-imagemagic-wrapper do process different image styles
var _ = require('underscore'),
inherits = require('util').inherits,
EventEmitter = require('events').EventEmitter,
imagemagick = require('imagemagick');
function ImageProcessor(options){
if(!options.image){
throw new Error("Provide an image to convert");
}
this.image = options.image;
if(options.styles){
this.styles = options.styles;
}
EventEmitter.call(this);
if(!options.process){
this.process();
}
};
inherits(ImageProcessor, EventEmitter);
ImageProcessor.prototype.process = function(){
var len = 0, options;
for(var style in this.styles){
len++;
(function(options, style, processer){
imagemagick.resize({
srcPath : processer.image,
format : options.format,
width : options.geometry.width || 0,
height : options.geometry.height || 0
}, function(err, stdout, stderr){
if(err){
console.warn(err);
} else {
processer.emit('style', style, new Buffer(stdout, 'binary'));
}
done(processer);
});
})(this.styles[style], style, this);
}
function done(processer){
if(--len === 0){
processer.emit('done');
}
}
};
module.exports = ImageProcessor;
var processor = new ImageProcessor({
image : params.files.cover.path,
styles : {
profile : {
geometry : { width : 600, height: 1000 },
format : 'jpg'
}
}
});
//callback for each style
processor.on('style', function(style, imageBuffer){
});
//callback if all styles are processed
processor.on('done' function(){
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment