Search code examples
imagemagick

How to change canvas to square without using -extent (retaining the longest edge)


After batch trimming a folder of images, how to then make the canvas square, whilst retaining the longest edge? I don't want to use -extent and make them all a fixed width.

Examples of desired output:

  • 800x1200 becomes 1200x1200
  • 1000x600 becomes 1000x1000
  • 1625x1600 becomes 1625x1625 etc....

So for example, if -squared was a function, it would be something like:

mogrify -path squared/ -trim -background white -gravity center  quality 75 -squared *.jpg

How to achieve this? I use ImageMagick v6.


Solution

  • If on ImageMagick 7, you can do the following with -extent to get the max of w and h.

    Input:

    enter image description here

    magick barn.jpg -background black -gravity center -extent "%[fx:max(w,h)]x%[fx:max(w,h)]" x.png
    

    enter image description here

    In ImageMagick 6, you can do something similar by using the viewport computations with -distort SRT, but you have to add the offset computations, since -gravity does not work with -distort SRT.

    convert barn.jpg -set option:distort:viewport "%[fx:max(w,h)]x%[fx:max(w,h)]+%[fx:(w-max(w,h))/2]+%[fx:(h-max(w,h))/2]" -virtual-pixel black -filter point -distort SRT 0 +repage y.png
    

    enter image description here