Change the color of an image with imagemagick

Micheal Perr picture Micheal Perr · Aug 28, 2012 · Viewed 10.5k times · Source

I want to change the foreground colors of an image using rmagick/imagemagick. To be more specific: I want to convert the black or the white glyphicons-halflings icons(which are included in twitter bootstrap) into darkblue glyphicons-halflings icons. (It would be nice if I could specifie a hexcolor or RGB color.)

I have no idea if this is even possible but I clicked through the imagemagick documentation and the only thing I found is convert --size 100x100 xc:skyblue glyphicons-halflings.png -composite foo.png, the problem is that this only works when you specifie a size and that it is changing the foreground color not the background color. Besides it is skyblue not darkblue.

So anyone who has an idea how I could convert the white or the black glyphicons-halflings into blue glyphicons-halflings icons? (Bonuspoints for rmagick/ruby code snippets)

Answer

Rafael Xavier picture Rafael Xavier · Jan 14, 2013

Quick answer:

convert glyphicons-halflings.png -alpha extract -background blue \
-alpha shape blue-glyphicons-halflings.png

blue-glyphicons-halflings.png

Note: instead of blue, you can use any named colors, or RGB, or RGBA, etc (see http://www.imagemagick.org/script/command-line-options.php#fill).

Explanation:

We "colorize" the icons in a two-step process:

  • Extract the alpha channel from the icons; (note: the color of the original icons doesn't matter, we're extracting its alpha channel)
  • Apply the above mask over a colored background of your choice;

For more information, read the following docs:

PS: The above solution has been researched while implementing jQuery ThemeRoller rewrite https://github.com/jquery/download.jqueryui.com/issues/77