Use imagemagick to convert opaque color to alpha

imagemagick

I have an image with a black background with white elements in the foreground. The image has smoothing, so there are 'in-between' pixels that aren't strictly black or white. I'd like to make the background transparent. I found several links on how to do this with imagemagick, but all of them strictly replace one color (say #000000FF" with full alpha "#00000000"). I want to preserve blending… so if there's a gray pixel "#777777FF", it'd get transformed into something like "#FFFFFF77", or whatever would make sense.

Does anyone know how to do this?

Best Answer

This article explains very well how to do this:
http://www.imagemagick.org/Usage/masking/#alpha

I wrote a small article about it on my blog:
http://mostlycoincidence.blogspot.se/2012/12/imagemagick-making-glyphs-transparent.html

Basically, what you want to do is create a mask, and then apply the mask to the image. You can do this in two steps:

$ convert image.png -colorspace HSB -separate -negate image_mask.png
$ convert image.png -alpha Off \
>    image_mask.png -compose CopyOpacity -composite \
>    PNG32:image_alpha.png

This will make white the transparent colour. To make black the transparency colour remove the -negate flag.

Related Question