Search code examples
imagemagicktransparencyalpha-transparency

How to cut out a rectangle (i.e. set it transparent) in imagemagick?


I combine three files, the 2nd and 3rd having some transparent areas, into one and this works fine:

convert image1.png image2.png image3.png -flatten image_combined.png

In addition to combining those pictures, I would like to cut out a rectangle in the middle of image1.png, leaving that area transparent, but can't do it. One (old) example I've found on a forum is:

convert image1.png -alpha set -region 40x30+15+5 -alpha transparent image2.png

When I try it (as-is, not even trying to mix it with my previously mentioned code), it doesn't work at all, outputting image2.png identical to image1.png (update: I'm using the ImageMagick v7)

Any help would be appreciated,

Michael


Solution

  • Here is an alternate to Mark's answer. (His answer only works for ImageMagick 7).

    Note that you cannot draw transparency. You can only flood fill some region to replace a color with transparency. But that is more complex.

    So the simple answer is to create a black square in a white background and add that image as the alpha channel. The white will keep the image opaque and the black will show as transparent.

    convert -size 100x100 xc:red red.png 
    

    enter image description here

    convert red.png \
    \( +clone -fill white -colorize 100 \
        -size 90x90 xc:black \
        -gravity center -composite \) \
    -alpha off -compose copy_opacity -composite \
    result.png 
    

    The above is Unix syntax for ImageMagick 6. For Windows, remove the \ from the parentheses and change the end of line \ to ^.

    For ImageMagick 7, replace convert with magick

    If your input image already has transparency, then you would have to extract its alpha channel and combine it with the rectangle image. Then replace the alpha channel of the input with the new combined alpha channel.