22

I am using the convert command for resizing the image

There are two versions

Following is the first one, the resultant image maintains the aspect ratio but the image does not necessarily be of size nxn

 convert temp.jpg -resize nxn temp.jpg

The second version

 convert temp.jpg -resize nxn! temp.jpg

It does not preserve the aspect ratio.

What I want is to preserve the aspect ratio, and fill the rest of the image with a desired RGB value to acheive the size nxn

Any ideas?

Thanks

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
Shan
  • 18,563
  • 39
  • 97
  • 132
  • Try with ffmpeg :https://trac.ffmpeg.org/wiki/Scaling%20%28resizing%29%20with%20ffmpeg – Rupesh Mar 16 '15 at 10:53
  • +1 to @Rupesh, pro tip, with many image manipulations, ffmpeg does the job faster than ImageMagick (especially when working with large image files) – Mint Jan 31 '22 at 22:37

1 Answers1

50

You need to use -extent to set the size of the canvas directly after you have resized, and the newly created area will be filled with whatever you set the -background to.

So, if you want the padding to be magenta, do this:

convert image.png -resize 100x100 -background "rgb(255,0,255)" -extent 100x100 out.png

If you want your image to appear "in the middle" of the output image, with the padding evenly spaced around the sides, add in -gravity center like this:

convert image.png -resize 100x100 -gravity center -background "rgb(255,0,255)" -extent 100x100 out.png

So, if we start with a wide blue image, that is 300x100 and has no chance of fitting properly in a square, as follows:

enter image description here

and we resize it with this:

convert image.png -resize 100x100 -gravity center -background "rgb(255,0,255)" -extent 100x100 out.png

we will get this

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Its a perfect answer and worked for my problem, sorry for being late as I was away, thanks for the answer! – Shan Mar 17 '15 at 17:45
  • I used this answer to make a square logo work for GSuite: `convert -resize 132x132 -gravity center -background "rgb(255,255,255)" -extent 320x132 in.png out.png` . The logo was resized to the smaller 132px square and ended up in the middle of the 320x132px white rectangle. Thanks @mark ! – Matt Feb 19 '19 at 04:57