Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! ');     }); 
like image 388
user3277539 Avatar asked Feb 06 '14 00:02

user3277539


People also ask

How do I resize an image without losing the ratio?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

How do I resize an image in node JS?

NodeJS – Resize() is an inbuilt function that is used to resize the images to the desired size. We can use resize to set the height and width using a 2-pass bilinear algorithm. It can resize an image into any size as declared by the user. We can take input from the user or resize it into fixed Width*Height size.


1 Answers

To achieve a resized, cropped image with a center gravity with the gm module, you can use something similar to this:

gm('/path/to/image.jpg')   .resize('200', '200', '^')   .gravity('Center')   .crop('200', '200')   .write(writeStream, function (err) {     if (!err) console.log(' hooray! ');   }); 

The '^' argument on the resize function will tell GraphicsMagick to use the height and width as a minimum instead of the default behavior, maximum. The resulting resized image will have either the width or height be your designated dimension, while the non-conforming dimension is larger than the specified size.

Then gravity function tells GraphicsMagick how the following crop function should behave, which will crop the image to the final size.

You can find detailed documentation for the GraphicsMagick options used by the gm module here: http://www.graphicsmagick.org/GraphicsMagick.html

like image 108
mikefrey Avatar answered Sep 30 '22 10:09

mikefrey