Colorizing Icons with `sed`

Illustration of creating colorized icons from a black one
Creating colorized versions of a base icon usually
calls for heavy Photoshop actions.

Recently I created an SVG file with some simple black-and-white icons I wanted to use in an application. The file contains a red background to differentiate between the single icon tiles, whose opacity is set to 0.3. The single icons all have an attribute fill="black".

The task was then to create CSS sprites from this file. The icons should be variated in four different colors and each one glued together in a single PNG file.

Taking advantage of the plain-text-ness of SVG this was a simple task for sed, with a little shell script around to create a PNG file:


sed -e 's/opacity="\.3"/opacity="0"/' -e "s/black/$1/" icons.svg \
| inkscape --export-png=first_icon.${1#\#}.png \
-a 0:0:24:24 /proc/self/fd/0

A sample invocation to create a red icon would look like

$ colorize_icon '#ff0000'

The trick with /proc/self/fd/0 forces Inkscape to accept stdin as input SVG file. Credit for this goes to keegan in the Ksplice company blog.

Line 3 reads in the SVG source. The two sed commands manipulate the source by

  1. setting the opacity to 0 for the helper background, letting it vanish, and
  2. changing all occurences of the string black to whatever is the first positional parameter.

The second line starts with a pipe, that puts the manipulated source in the stdin stream for the inkscape command. Inkscape is used, without a GUI, to render the portion between 0,0 and 24,24 (Inkscape’s coordinate system defines 0,0 as lower left corner!) as the file first_icon.<COLORNAME>.png.

The curly braces and hashes are used to remove the # character from the color given as positional parameter by utilizing Bash’s built-in string manipulation.