user3277539 user3277539 - 4 months ago 116
Node.js Question

Resize and crop image and keeping aspect ratio NodeJS & gm

I've been trying to create some thumbnails using the

gm
package from NodeJS, but I'm out of lucky. I need to resize images bigger than 600x600 (could be any width/height, starting from the given one) but when I pass the size to gm, it creates an image that doesn't have the same size I requested.

For example, given this code, I assume that running
node app /path/to/image.png
I'll receive an image with size of 200x100, but instead I got, say, an image of 180x100 or 200x90...

gm(fileLocation)
.thumb(200, 100, 'processed.' + process.argv[2].split('.').pop(), function() {
console.log("Done!");
});


I've also tried with the resize option. There's even an option to force the size, but the aspect ratio of the output goes horrible...

gm('/path/to/image.jpg')
.resize(353, 257)
.write(writeStream, function (err) {
if (!err) console.log(' hooray! ');
});

Answer

Try with imagemagick package for NodeJS: https://github.com/yourdeveloper/node-imagemagick

im.crop({
    srcPath: process.argv[2],
    dstPath: 'cropped.' + process.argv[2].split('.').pop(),
    width: 200,
    height: 200,
    quality: 1,
    gravity: 'Center'
}, function(err, stdout, stderr){
    if (err) throw err;
    console.log('resized ' + process.argv[2].split('/').pop() + ' to fit within 200x200px');
});

Update: Please note that the node-imagemagick package hasn't been updated in quite a long time. Please consider Freyday's answer since it's most up-to-date.