Search code examples
imagemagickimagemagick-convert

Drawing centered rectangle with ImageMagick


Using the CLI, I'd like to add a black rectangle to an image that is 1) centered and 2) X pixels from every edge.

Basically, I almost want the opposite of -border (instead of adding a border of a certain color, I'd like to keep X pixels of my image as border, then paint everything else inside black. Also, image size should not change).

Something that I expected to work but didn't was:

convert myImage.jpg -fill black -draw "rectangle 10,10 %[fx:w-20],%[fx:h-20]" outImage.jpg

...for a "border" of 10 pixels. It looks like -draw doesn't accept FX operators or attributes, although I found somewhere (like in How can I use imagemagick attributes in the draw rectangle command?) that it should in IM 7.x (which is what I'm using).


Solution

  • In ImageMagick 7, you should use magick and not convert. Using convert will make calls to ImageMagick 6 which does not support the fx in-line operations. In ImageMagick 7, do it this way for a 10 pixel border of image about the black rectangle:

    Input:

    enter image description here

    magick lena.jpg -fill black -draw "rectangle 10,10 %[fx:w-11],%[fx:h-11]" result.jpg
    


    enter image description here

    Note that one should use 11 rather than 10, since the last pixel in the image is w-1,h-1. Numbering starts at 0. So I have corrected my original answer above.