Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imagemagick replace color but keep transparency

Tags:

imagemagick

I would like to replace all instances of black in a PNG logo with another color. I tried:

convert source.png -fill #123456 -opaque black out.png

But the logo has some transparent black pixels that are not converted. How can I change EVERY black pixel, but keep transparency on each?

like image 855
emilecantin Avatar asked Feb 27 '13 19:02

emilecantin


1 Answers

convert in.png xc:"#ff0000" -channel RGB -clut  out.png

This will do the job. Provided that in.png has an alpha channel, the RGB channels in in.png will be replaced with red (#ff0000) while keeping the alpha channel untouched.

What happens here? in.png is the first input image. xc:"#ff0000" is the second input image (the xc: special file is interpreted by ImageMagick as an image all filled with the given color). The -clut option ("Color Look Up Table") interprets the second image as a lookup table and applies it to the values in the first image. Since the second image is monochrome, every color in the first is mapped to red in this example. The last file name (out.png) is interpreted as the output file.

Why does -clut not affect the alpha channel? Well, you can set the affected channels with the -channel option. It must go before the -clut. RGB is what we want here.

like image 70
fieres Avatar answered Oct 20 '22 00:10

fieres