Micheal Perr
Micheal Perr

Reputation: 1895

Change the color of an image with imagemagick

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)

Upvotes: 19

Views: 12089

Answers (3)

Rafael Xavier
Rafael Xavier

Reputation: 2899

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

Upvotes: 39

David Douglas
David Douglas

Reputation: 10503

In addition to sguha's answer - here's the Ruby version (albeit for QuickMagick):

require 'quick_magick'
source = "images/source.png"
dest = "images/saved.png"
foreground = "0000ff" #hex code for your colour

QuickMagick.exec3("convert #{source} -fill \"##{foreground}\" +opaque \"##{foreground}\" #{dest}")

Upvotes: 3

sguha
sguha

Reputation: 2227

From http://www.imagemagick.org/Usage/color_basics/#replace, you can replace all colors in the image that are not darkblue with darkblue with the following command:

convert glyphicons-halflings.png -fill darkblue +opaque darkblue glyphicons-halflings.png

If you want to do it in ruby, I'd recommend using the Minimagick gem https://github.com/minimagic/minimagick which simply calls convert on the command line. From my experience, not all functionality has been ported from the command line to RMagick

Upvotes: 5

Related Questions