imageresizeimagemagick

Create square for multiple images of different sizes


I have several png images of different sizes, some are squares and some rectangles (one side larger than other), for example

1440x1440
1280x985
1440x1389
1440x540
1440x1946
1412x1388

I'd like to center each image in a white square depending on its larger side, for example:

I can do what I want saying specifically the output size of 1440x1440 with this command (following what they say in this question).

magick -define jpeg:size=1440x1440 input.png -thumbnail '1440x1440>' \
          -background white -gravity center -extent 1440x1440 output.png

and with loop like this:

for f in *.png 
do 
magick -define jpeg:size=1440x1440 "$f" -thumbnail '1440x1440>'  \
-background white -gravity center -extent 1440x1440 "$f"_out.png 
done

But how can I dynamically identify the larger side of each image to create a square corresponding to the larger side of each image?

I hope make sense. Thanks


Solution

  • With ImageMagick 7 you can process all the PNG images in a directory, center them on a square canvas with the dimensions of the longer side of each image, using a command like this...

    magick mogrify -gravity center -background white -extent 1:1# *.png
    

    Note: That uses IM's "mogrify" tool, which will overwrite all the originals in the directory with the results. For safety, make a backup copy of the original images.

    To place a single image on a white background, a square with the dimensions of the longer side of the input, this command should work...

    magick input.png -gravity center -background white -extent 1:1# result.png
    

    EDITED TO ADD:

    As mentioned by fmw42, the use of "1:1#" is a fairly new addition to IMv7 and will not work in some older v7 versions. This command uses FX expressions to achieve the same result, so it will work with any version of IMv7 on individual images...

    magick input.png -gravity center -background white -extent "%[fx:max(w,h)]x%[fx:max(w,h)]" result.png
    

    The use of the FX expressions prevents it from being used with the "mogrify" tool.