Last active
December 14, 2015 05:49
-
-
Save wemakeweb/5038120 to your computer and use it in GitHub Desktop.
node-imagemagic-wrapper do process different image styles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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