Search code examples
imagemagickimagemagick-convert

Pad image with transparency so it is sized as multiplies of 300 in both directions (ImageMagick 7)


My issue is sort of similar to this issue: How to square an image and pad with transparency from the commandline (imagemagick), but I don't want to square the image, only scale it upwards to the nearest multiplier of 300 in each direction, padded with transparency. The original image should be centered within this new padding.

Example:

Input image: Width 1004 px, Height 250 px Output image: Width 1200 px, Height 300 px, original image centered.

I'm trying to make this happen with the Mac Terminal if that matters.

I've managed to do the transform in the link above, as well as a list of other necessary transforms, but I'm having a hard time working with the IM variables provided, together with mathematical functions for rounding a floated number, together with a distort:viewport function, which seems to be the one I should be using?


Solution

  • I think you want this:

    magick -gravity center start.png -background yellow -extent "%[fx:int((w+299)/300)*300]x%[fx:int((h+299)/300)*300]" result.png
    

    So, if we start with your dimensions of 1004x250:

    enter image description here

    you'll get this:

    enter image description here

    Obviously you'll want to replace yellow with none for a transparent border, but I want the extent visible on StackOverflow.

    If you are using a different multiple, the 299 in my formula is just multiple - 1. So, you could re-cast the answer as this:

    MULT=300
    magick -gravity center start.png -background yellow -extent "%[fx:int((w+$MULT-1)/$MULT)*$MULT]x%[fx:int((h+$MULT-1)/$MULT)*$MULT]" result.png
    

    Or, if you don't like the ugly %[fx:...] expression you can do all the maths in the shell:

    # Establish the multiple
    MULT=300
    # Get existing image width and height
    read w h < <(magick -format "%w %h" start.png info:)
    # Calculate new width and new height
    ((NW=((w+MULT-1)/MULT)*MULT))
    ((NH=((h+MULT-1)/MULT)*MULT))
    magick -gravity center start.png -background yellow -extent "$NWx$NH" result.png