Search code examples
imagemagick

Applying a colour gradient only to the non transparent area of an image in Image Magick


I would like to apply a coloured gradient to an image while maintaining the transparency of the original image, so that I can show the image on a map, from this original image to this output image (but without the map)

My understanding is that I would need to extract the alpha channels of the image using +clone -alpha extract then apply the gradient to that then composite the gradient on top of the original image.

Currently I've tried adopting a couple of other stackoverflow answers and have managed to output the extracted alpha channels but cannot get the gradient to work.

This is what I have so far:

convert normal.png -write MPR:orig -alpha extract
\( +clone -define gradient:"rgba(0,126,15,5)"-"rgba(255,0,0,5)" \) \
-compose multiply -composite -write alpha.png \
MPR:orig +swap -compose copyopacity -composite result.png

Solution

  • Here is a command that should do very nearly what you describe...

    magick input.png -size %wx%h -define gradient:angle=90 ^
       gradient:green-red -channel rgb -compose multiply -composite result.png
    

    By specifying -channel rgb ahead of the composite operation it should only affect the color channels and maintain the transparency. The output from running that command on fmw42's input image using ImageMagick v7.1.0-24 on Windows (for a *nix OS change the continued-line caret "^" to a backslash "\")...

    enter image description here

    If you're following that with other operations you may want to reset the channel with +channel and the compose method with -compose over after the -composite and before continuing the command.