Question

I need to create an image to be used as a rollover background image. It's a circular pattern that is split into 8 pieces. Here's a screengrab of the main image (png with transparency):

main-image

And here's a screengrab of the mask image. It's the same size as the main image and features 'pie' pieces in order to mask all but the sector that is being hovered over.

masked-image

I'm including screengrabs, as I believe the answer should be pretty simple (aren't all answers simple when you know them?!) so I'll save bandwidth, but I can upload the original files if it's helpful.

Here's the command I'm using to create the new masked image:

convert main.png \( mask.png -colorspace gray -alpha off \) \
-compose copy-opacity -composite new.png

The trouble is that the new image created has flattened the original image's alpha to a black background:

new-image

How do I get Imagemagick to preserve the original png's transparency?

Was it helpful?

Solution

You want masked composition to do this. http://imagemagick.org/Usage/compose/#mask

The technique is to compose the original image (the src) onto a fully transparent image of the same size (the dst), using a mask to limit composition area (the mask). It is a special case of the -composite operator, and involves 3 images, rather than 2 like the rest of the compose methods. You don't specify any -compose mode for this.

A quick way to get the fully transparent dst that you need for this technique is to clone the src image and zero out its alpha channel, then swap the order of src and dst so that they are in the right order for the -composite operation to follow:

convert main.png -alpha on \( +clone -channel a -fx 0 \) +swap mask.png -composite out.png

OTHER TIPS

I was not satisfied with retroj's solution as it seems to ignore the grayscale of the mask.

This one worked for me:

composite -compose Dst_In \( mask.png -alpha copy \) main.png -alpha Set PNG32:result.png

or

convert -compose Dst_In \( mask.png -alpha copy \) main.png -alpha Set -composite PNG32:result.png

Dst_In method multiplies the alpha channels of two images. The trick here is to convert the grayscale mask to an alpha channel for it which is done with -alpha copy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top