Created
August 5, 2012 19:33
-
-
Save arian/3266825 to your computer and use it in GitHub Desktop.
Cropping images with nodejs streams and imagemagick
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 spawn = require('child_process').spawn; | |
var Stream = require('stream'); | |
/** | |
* crops and resizes images to our desired size | |
* @param {Stream} streamIn in stream containing the raw image | |
* @return {Stream} | |
*/ | |
exports.cropImage = function(streamIn){ | |
var command = 'convert'; | |
// http://www.imagemagick.org/Usage/resize/#space_fill | |
var args = [ | |
"-", // use stdin | |
"-resize", "640x", // resize width to 640 | |
"-resize", "x360<", // resize height if it's smaller than 360 | |
"-gravity", "center", // sets the offset to the center | |
"-crop", "640x360+0+0", // crop | |
"+repage", // reset the virtual canvas meta-data from the images. | |
"-" // output to stdout | |
]; | |
var proc = spawn(command, args); | |
var stream = new Stream(); | |
proc.stderr.on('data', stream.emit.bind(stream, 'error')); | |
proc.stdout.on('data', stream.emit.bind(stream, 'data')); | |
proc.stdout.on('end', stream.emit.bind(stream, 'end')); | |
proc.on('error', stream.emit.bind(stream, 'error')); | |
streamIn.pipe(proc.stdin); | |
return stream; | |
}; | |
// usage | |
var fs = require('fs'); | |
var streamIn = fs.createReadStream('./image.jpg'); | |
var streamOut = fs.createWriteStream('./resized.jpg'); | |
exports.cropImage(streamIn).pipe(streamOut); |
@AndreasFurster same here :D
Hello!
Do you know how to handle the output format of the image? -format and -define do not work.
It outputs the same format it receives.
@BrunildaNinox I am also experiencing the same issues. Did you find any solution?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't one of the
data
events on line 28 or 29 need to beerror
?And yes, 7 years later, your gist is still very useful! 🥇