Archive for the ‘Perl’ Category

Convert an image to XPM format suitable for embedding in Perl

Monday, March 24th, 2008

Recently I was working on a single file GTK/Perl program which used an external image file for a logo. I didn’t want to distribute the image file along side the actual program as this was a little messy and probably not worth it for just one logo. So before doing away with the logo, I investigated if there were any possible ways to embed the image data in the Perl code.


It seems that the defacto standard for representing image data in ASCII format is XPM or X PixMap. This is usually represented in a way that is compatible with programs written in C (the XPM2 format does away with any language specific details).

Getting the XPM data

Getting the image data in XPM format is relatively easy if you have the ImageMagick suite of tools installed. If so, then just run the following:

convert inputfile outputfile.xpm

The trick here is to make sure your output file ends with a .xpm extension. ImageMagick will recognize this and do the conversion to XPM for you.

Converting to Perl code

As you might have noticed if you looked at the resulting XPM file, it is in standard C notation. Not very useful for a Perl program. Never fear, a sprinkling of substitution and regex magic will bring us home.

“s/^static.*$/my \@xpm_image = (/”

In order from top to bottom we have:

  • Escape all the single quotes
  • Convert double quotes to single quotes
  • Remove lines that start with a C-style comment
  • Reformat the variable declaration for Perl
  • Fix up the closing brace on the array definition.

With all these substitutions done, we can embed the resulting code in a Perl program and use it with functions that expect XPM data, Gtk2::Gdk::Pixbuf->new_from_xpm_data() for example.

All together now…….

Ok, lets put it all together into a Bash script. As with any shell script, we need the shebang on the first line:


then we have filename definitions:

inputfile=$1 # $1 is the first argument passed to the script

ImageMagick conversion and rename:

convert $inputfile $xpmfile
mv $xpmfile $perlfile

and the substitutions (the “i” argument means substitutions are done in place, i.e. there is no separate output file)

perl -pi -w -e “s/\’/\\\’/g” $perlfile # All single quotes get escaped
perl -pi -w -e s/\”/\’/g $perlfile # Double quotes -> single quotes
perl -pi -w -e “s|^/\*.*\n$||” $perlfile # Remove c-style comment lines
perl -pi -w -e “s/^static.*$/my \@xpm_image = (/” $perlfile # Change variable declaration
perl -pi -w -e “s/^};$/);/” $perlfile # Change closing brace of array

If you want to download or view the script in it entirety, have a look at img2xpm_perl at