Replace a colour in an image with imagemagick
2 min read

Replace a colour in an image with imagemagick

Replace a colour in an image with imagemagick

I had to change the colour of some monochrome icons for a personal project, from black to something else (i.e. not black). I've tried in python with PIL. Unfortunately, my attempts to use ImageOps failed miserably, because I'm working with RGBA images, not RGB :(. Of course, one could separate the RGBA in two, perform the operation and replace the RGB channels with the updated variants, or even do a pixel-by-pixel search (aka overkill). Since this is more or less a one-off operation, I've looked at other ways. I remember a loong time ago doing batch processing with Debabelizer. From my command line days, I remembered that you could theoretically use ImageMagick to perform relatively simple conversions and compositing. Unfortunately, convert is like a mammoth; it does everything in one command! Therefore, figuring out what needs to be done is not really straight forward... After some investigation, I've come up with the following command:

convert SOURCE.png -fuzz 10% -fill red +opaque black -fill red -opaque black DESTINATION.png

The key component is -fill red +/-opaque black, which tells the image to replace the black with red. The opaque command takes care of replacing the pure black and the more transparent bits (I'm not 100% sure how it works, but if you omit one either the opaque or the semi-transparent pixels don't get replaced).

Source Destination
c_1 c_2

You can, of course use custom colours, not pre-defined by replacing e.g. black with e.g. rgb(2,90,164) in the command. You can do some aliasing (it's a shell command, after all). This is particularly useful when doing batch processing and you might want the ability to easily replace a colour, or the tolerance...

Note: This is a post transferred from Laurii for historical and consolidation purposes.