Resize image to exact size by maintaining aspect ratio nodejs

1.5k Views Asked by At

I want to resize image to an exact size by maintaining aspect ratio and filling the empty space with transparency using nodejs.

I am able to do it using canvas. But due to some server os issues I can not use canvas.

I tried with imageMagick and gm. But couldn't find any option like these. Please show me a way to do this.

Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

In ImageMagick, you can resize and fill to the exact size by

convert image -resize WxH -background none -gravity center -extent WxH output

Input:

enter image description here

Here I will make the background black so you can see that if fills it out.

convert lena.jpg -resize 400x300 -background black -gravity center -extent 400x300 lena1.jpg


enter image description here

0
On

In case you have been successful using the canvas for resizing images, you can check out https://github.com/Automattic/node-canvas this repo.

As already mentioned you also resize images using ImageMagick by processes in NodeJS ( http://www.imagemagick.org/Usage/resize/ )

convert dragon.gif  -resize 64x64  resize_dragon.gif

In case you have a lot of images, I would suggest that you write a terminal script ( NodeJS can achieve that as well ).

I hope it helps, in case you have more queries, feel free to ask.