imagemagickimagemagick-convert

How to resize an image in imagemagick but keep an aspect ratio constant


I am trying to resize an image (using imagemagick) to keep it's current aspect ratio but fit it into a 4/3 container.

This is the command I have so far:

magick convert ./horse.jpeg -background white -gravity center -extent 4/3 ./hourse_output.jpeg

This is what I'd like: horse. As you can see, the image is "put into" a 4/3 container.


Solution

  • My error. The aspect ratios such as 4:3 in ImageMagick -extent will only crop and not pad.

    See my bash unix script "aspectpad" at http://www.fmwconcepts.com/imagemagick/index.html, which does what you want I think.

    Nevertheless, here is a partial solution for how to do it. But this only works for landscape mode input. Also only with ImageMagick 7 due to the use of inline arguments for -extent. You would have to modify it for portrait mode.

    Input (aspect 2:1 = 2/1 = 2):

    enter image description here

    magick barn_2to1.jpg -set option:wd "%[fx:(4/3)>(w/h)?(4/3*h):w]" -set option:ht "%[fx:(4/3)>(w/h)?h:(w/(4/3))]" -gravity center -background black -extent "%[wd]x%[ht]" result.jpg
    


    Output (aspect 4:3 = 4/3 = 1.33):

    enter image description here

    Note, that I used background of black so that it was visible here. Change to any other color you want.

    If the input landscape aspect is larger than 4:3 (4/3), it will pad on top/bottom. If the input landscape aspect is smaller than 4:3, it will pad on left/right.

    Input (aspect=1:1 = 1/1 = 1):

    enter image description here

    magick lena.jpg -set option:wd "%[fx:(4/3)>(w/h)?(4/3*h):w]" -set option:ht "%[fx:(4/3)>(w/h)?h:(w/(4/3))]" -gravity center -background black -extent "%[wd]x%[ht]" result2.jpg
    


    enter image description here