Search code examples
image-processingimagemagickimage-manipulation

Imagemagick: transform portrait and landscape aspects to square images (with blurred stripes)


To convert a landscape image to a square with blurred edges I'm using the following command:

magick input.jpg -fuzz 15% -trim +repage \( -clone 0 -resize 100x`identify -format "%[fx:w/h*100]" $1`% -blur 0x10 \) +swap -gravity center -compose over -composite squared_landscape.jpg

The result looks fine: Processed landscape image However trying the same for portrait images with slightly changed parameters (swap of the h/w division to get the aspect ratio > 1) doesn't provide the same result:

magick input.jpg -fuzz 15% -trim +repage \( -clone 0 -resize `identify -format "%[fx:h/w*100]" $1`x100% -blur 0x10 \) +swap -gravity center -compose over -composite squared_portrait.jpg

executing the nested bit returning the aspect ratio identify -format "%[fx:h/w*100]" input.jpg with an image of 2000x2525px results in an aspect ratio of 126.25 which should result in a square again. However executing the command nested like above doesn't produce the desired result.

Ultimately the idea would be to use the same generic line to format portrait and landscape images to the desired squared outcome.


Solution

  • Here is another simple and effective method for expanding the canvas to a square, and filling any added background area with the same image blurred. This uses ImageMagick v7 in Windows CLI syntax. Note: This command will require some tweaking if the input is wider or higher than 2:1 or 1:2.

    Here the result with a portrait oriented image...

    magick monet.jpg -gravity center ^
       ( +clone -splice "%[fx:w<h?h-w:0]x%[fx:h<w?w-h:0]" -blur 0x12 ) ^
       +insert -composite result1.png
    

    enter image description here

    And the exact same command with a landscape oriented image...

    magick barn.jpg -gravity center ^
       ( +clone -splice "%[fx:w<h?h-w:0]x%[fx:h<w?w-h:0]" -blur 0x12 ) ^
       +insert -composite result2.png
    

    enter image description here

    The command clones the input inside the parentheses, and adds enough to the center of the canvas, either horizontally or vertically, to make it square. Also inside the parentheses it adds the blur.

    After the parentheses, that squared and blurred image is swapped to the back. Then it finishes by compositing the input image centered over that background.

    To use in a Windows BAT script, double the percent signs "%%". To use on a *nix OS, escape the parentheses with backslashes "\(...\)", and change the continued-line carets "^" to backslashes "\". I haven't tested on a *nix, so there may be other special characters that need quoting or escaping.