'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 1:[1]
Perhaps this is what you want in Imagemagick. Note that when using gradient:, you have to specify -size WxH for it. So I use -sparse-color barycentric to form the gradient from a clone of the input.
Input:
convert normal.png \
\( +clone -alpha extract -write MPR:alpha +delete \) \
\( -clone 0 -alpha off -sparse-color barycentric "0,0 rgb(0,126,15) %w,%h rgb(255,0,0) %w,0 rgb(255,0,0)" \) \
-compose multiply -composite \
MPR:alpha -alpha off -compose copyopacity -composite result.png
Result:
Line 1: Read the input
Line 2: Copy the input, extract the alpha and save to mpr:, then delete the alpha (not the mpr:)
Line 3: Copy the input and create a gradient for over that image
Line 4: Composite the gradient by multiplication with the input
Line 5: Read back the mpr:alpha and put it into the alpha channel of the input in place of the original alpha channel
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fmw42 |


