How to colorize a black-transparent PNG icon with ImageMagick
Asked Answered
E

3

9

How do I a colorize a black PNG image that has a transparent background using ImageMagick?

Use case:
You have several PNG images like this:
Source image

And I want to colorize them like this:
Wished result

I want to use ImageMagick's convert command, allowing for scripting to process hundreds of icons at a time.

Enfleurage answered 22/2, 2016 at 12:54 Comment(0)
E
5

You can use one of the following commands:

$ convert input.png +level-colors "red", output.png
$ convert input.png +level-colors "rgb(255,0,0)", output.png
$ convert input.png +level-colors "#ff0000", output.png

Note that the , character is important here. On the left side of the , character we tell convert which color should replace black and on right side what color should replace white. Therefore nothing should be given after the , character.

Source

Enfleurage answered 22/2, 2016 at 12:54 Comment(4)
How can I edit these commands so that they preserve alpha-transparency?Overstride
I can make it in two parts, first applying yours and then convert output.png -transparent white result.png. But can this be achieved in one command?Overstride
It seems to me that my command preserved transparency, but do you mean that it does not work with say, 50% transparency? (most pixels in my icons have 100% or 0% transparency so I could have missed that)Enfleurage
I found that 100% transparent icons are preserved. Thanks for this excellent tip! Super useful to quickly create variations of icons I've previously purchased licenses forFixing
M
5

... how do I colorize black & transparent PNG images [...] to colorize them like this [...] using ImageMagick

The -fill <COLOR> option works fantastic for this purpose. You can replace "#1bbfc9" with a human-readable name (e.g. "red") or an HTML color code.

convert target-black.png -fill "#1bbfc9" -colorize 100 target-blue.png

... allowing to script and process hundreds of icons at a time

Using the find command, you can recurse hundreds.
Warning: This will replace the originals.

find path/to/files  -iname '*.png' -exec convert "{}" -fill "#1bbfc9" -colorize 100 "{}" \;
Megadeath answered 29/8, 2019 at 15:47 Comment(0)
F
1

With ImageMagick, you can process a whole folder of images at one time with mogrify rather than convert if you want all the same color. Create a new output directory to hold the colorized files. Then cd to the folder holding your images.

cd path_to/image_folder
mogrify -format png -path path_to/new_folder -fill "cyan" -colorize 100 *.png


Where replace path_to with your actual path.

You may use color names, hex colors or rgb(...) colors in the fill command, but enclose them in quotes on Linux/Mac OSX. Quotes are not needed for Windows, but should not cause any issues if double quotes.

See mogrify

Fenrir answered 29/8, 2019 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.