Maintain cnavas aspect ratio

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
leupi

Maintain cnavas aspect ratio

Post by leupi »

I am resizing lots of images with varying aspect ratios. The resized images all need to be 192x128, 384x256, and 768x512 (which all are the same aspect ratio). Most of the original images share that ratio; although, some do not. If I resize a 400x400 image to 196x128 it actually becomes 128x128, which makes sense. Is there a way to have a 32 px border on both the left and right added to maintain the 192x128 ratio? Of course this border would need to be larger or smaller, top and bottom, left and right, depending on the original image ratio.

Thanks,
Todd
Bonzo
Posts: 2971
Joined: 2006-05-20T08:08:19-07:00
Location: Cambridge, England

Re: Maintain cnavas aspect ratio

Post by Bonzo »

You do not say how you are using Imagemagick and you would need to do some calculations on the image to find out the size of the image so you know which border/canvas to use.

Code: Select all

\( input.jpg -resize 250x250 \) -size 300x250 xc:black -gravity center +swap -composite 
This will resize an image to 250x250 maintaining the aspect ratio and place it in the center of a 300x250 black background.
User avatar
anthony
Posts: 8883
Joined: 2004-05-31T19:27:03-07:00
Authentication code: 8675308
Location: Brisbane, Australia

Re: Maintain cnavas aspect ratio

Post by anthony »

See IM Examples, Thumbnails, Padded Images
http://imagemagick.org/Usage/thumbnails/#pad
which has many methods.

The Composite method is the oldest, most logical, and slowest

The extent method should be the fastest and simplest.
It even works for "resize to fill space", using the new '^' resize flag.

convert image400x400.png -resize 196x128 \
-gravity center -background black -extent 196x128 \
padded_image.png

PS: using a '@' flag will let you get a mix between "resize to fit", and "resize to fill", but the number of pixels needs to be calculated!

I feel a new IM example comming on!
See http://imagemagick.org/Usage/thumbnail/#bestfit
in a couple of days.
Anthony Thyssen -- Webmaster for ImageMagick Example Pages
https://imagemagick.org/Usage/
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Maintain cnavas aspect ratio

Post by fmw42 »

Post Reply