Resize and crop image and keeping aspect ratio NodeJS & gm
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.
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
Another solution without external libraries (except by imagemagick) is create your own solution:
var exec = require('child_process').exec;
resize = function (image) {
var cmd = 'convert ' + image.src +
' -resize ' + image.width + 'x' + image.height + '^' +
' -gravity center -crop ' + image.width + 'x' + image.height + '+0+0 ' +
image.dst;
exec(cmd, function(error, stdout, stderr) {
if(error) {
console.log(error);
}
});
}
And then call it:
resize({
src: sourceFile,
dst: destinyFile,
width: 320,
height: 240
});
It will allow your custom parameters of quality, crop, watermark, etc...