Use ImageMagick to place an image inside a larger canvas

Viewed 40940

Getting started with ImageMagic and trying to find a way to do this... If an image is less than 50 pixels tall or 50 pixels wide, I'd like to place it (un-scaled) in the horizontal/vertical center of a new 50x50 pixel canvas on top of a white background - and save that as the new image. Anyone know if this is possible with ImageMagick? Thanks!

8 Answers

You can use single composition to do this. So it would look something like this:

convert -size 50x50 xc:white null: ( my_image.png -coalesce ) -gravity Center -layers Composite -layers Optimize output.png

If an image is less than 50 pixels tall or 50 pixels wide

In my case, the images were much larger than the destination canvas, and weren't square. So I resize them proportionally to fit inside. Example:

convert in.png -resize 46x46 -background none -gravity center -extent 50x50 out.png

The 46x46 limit ensures a 2 pixel margin minimum. Note that the above does not distort the image, e.g. a rectangle does not become a square.

I used background none for a transparent background, but you can choose a solid color instead.

Related