1
votes

Is it possible to set the alpha channel of an image according to a gradient with ImageMagick?

I'd like the pixels on the left border of an image to be 100% transparent, and the ones on the right border to be 100% opaque, and with the ones in the middle having progressively lower transparency values.

Or in a more general case - given a grayscale image, set the alpha channel of another image as a function of the B&W values (black = 100% alpha, white 0% alpha).

2

2 Answers

2
votes

Simple. You would use -composite CopyOpacity to set the alpha channel from a gradient mask.

Given I have the following images. image.png & transparent_mask.png

image transparent_mask

We can set the image transparency (where black is alpha, and white is opaque) by copying values from the mask image to the input image alpha channel.

convert image.png transparent_mask.png -compose CopyOpacity -composite output.png

output

1
votes

With ImageMagick you can use -sparse-color to apply a gradient only to the alpha channel to get the result you describe.

convert in.png -alpha set -background none -channel A \
    -sparse-color barycentric "0,0 none %[w],0 white" +channel out.png

That command starts by activating the alpha channel and setting the background color to transparent. Then it uses -channel A to apply the following operation only to the alpha channel. The -sparse-color operation tells it to start with transparent at the far left edge, pixel 0,0 and graduate to opaque at pixel %[w],0. The %[w] means the width or far right edge.

Although there are many ways to accomplish the effect you've described, by using -sparse-color you can easily make the gradient start and end at any positions on the image without having to create any intermediate masking images.