Search code examples
imagemagicktransparencygifmaskanimated-gif

Apply cropping mask to the animated gif with a transparent background


I have some animated GIF with a transparent background, e.g:

https://i.sstatic.net/DNFWZ.gif

I also have a mask PNG file, where some pixels are transparent, which I want to apply to the GIF, e.g

https://i.sstatic.net/yLDxa.png

I want all transparent pixels on the mask to be transparent on the GIF (for each frame) - just like the image below, but animated AND keep the original GIF transparent pixels.

https://i.sstatic.net/dqSzT.png

How it can be achieved with ImageMagick?


Solution

  • Here is one way to do that in ImageMagick 6. First multiply the mask with the alpha channels of the animation. Then put the new alpha channels back with the animation.

    I note that your mask, has the circle in the alpha channel of the PNG and the underlying image is totally black. So the important part of your mask image is its alpha channel.

    Animation:

    enter image description here

    Mask:

    enter image description here

    convert lips.gif -coalesce -alpha extract null: \( lips_mask.png -alpha extract \) -compose multiply -layers composite alpha.gif
    
    convert lips.gif null: alpha.gif -alpha off -compose copy_opacity -layers composite lips_masked.gif
    

    enter image description here

    If using ImageMagick 7, change convert to magick.