Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageMagick convert resize by the smaller dimension?

Tags:

imagemagick

The following command resizes the larger dimension to 256:

convert -resize 256x256 in.jpg out.jpg

For example, if in.jpg is 1024x512, it resizes it to 256x128.

Is it possible to resize the smaller dimension to 256 (while keeping the aspect ratio) with ImageMagick convert? (I need 512x256)

If not, is there any other easy command line solution?

like image 824
Mohammad Moghimi Avatar asked Nov 05 '25 09:11

Mohammad Moghimi


2 Answers

The fill area flag ^ seems to do exactly what you want:

convert -resize 256x256^ in.jpg out.jpg

If you're on Windows:

The Fill Area Flag ('^' flag) is a special character in Window batch scripts and you will need to escape that character by doubling it. For example '^^', or it will not work.

This only works with ImageMagick 6.3.8-3 and above. For older versions, use this trick.

like image 161
nwellnhof Avatar answered Nov 09 '25 09:11

nwellnhof


Maybe the command I suggested in my comment will work, namely

convert in.jpg -resize x256 out.jpg

Or, if you actually want to identify the smaller dimension and resize that explicitly, this should do the trick

#!/bin/bash
image=$1
cmd="x256"
[ $(identify -format "%[fx:w<h?1:0]" "$image") -eq 1 ] && cmd="256x"
convert "$image" -resize $cmd out.jpg

I preset the command to resize by height at line 3. Then I ask ImageMagick to output 1 if the image is taller than wide, and if it is, I change the resize command to resize by width. Then, finally, I do the actual resize. You can re-cast the script various ways to make it shorter, or leave it explicit.

E.g.

if [ $(identify -format "%[fx:w<h?1:0]" in.jpg) -eq 1 ]; then 
   convert in.jpg -resize x256 out.jpg; 
else 
   convert in.jpg -resize 256x out.jpg; 
fi
like image 29
Mark Setchell Avatar answered Nov 09 '25 09:11

Mark Setchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!