Peter’s Programming Notes: ImageMagick Hints

ImageMagick Hints

I sometimes use ImageMagick/PerlMagick for scripting image manipulation. The documentation is not terrible, but it misses a lot of bits. I will try to document any bits I eventually decipher that are not clear from the docs.

Contents

Geometry

The typical geometry value is something like 10x20+5+6 which means width 10, height 20, start at x 5, y 6. But gemoetry can include all sorts of random things, including flag symbols % (Percent), ! (Aspect), < and >, @ (Area), as well as Decimals. The numbers can be separated by x (or X), comma (,), or slash (/). These are all parsed by a single routine (ParseGeometry in geometry.c) and what the five numbers actually mean varies depending on who is calling the routine.

Colors

SetAttribute( "pixel[]" ) takes either four numbers separated by commas (if the parameter includes a comma), or a color. Unfortunately, many colors have commas in them (eg rgba(1,2,3,4)) and these are parsed as four numbers instead of a color, which seems to be a bug. However, because of the way ParseGeometry works, you can almost always replace the commans with slashes (eg rgba(1/2/3/4)) to work around this problem.

A color (as defined by QueryMagickColor in color.c) can be any of:

Adding an Alhpa Channel

This one had me stumped for ages, until I eventually learned that ImageMagick sometimes calls the alpha channel a matte. To add an alpha channel, simply $image->Set( 'matte'=>'True' );. Without this, if the image is created from a source without an alpha channel, calls to $image->Set("pixel[$x,$y]"=>"$r,$g,$b,$a"); will simply bounce any attempt to alter the alpha channel component.

Also be aware that ImageMagick is a bit schitophrenic about whether it is transparency or opacity (ie, GetPixels(RGBA) will return 65535 for fully opaque, but Set pixel expects 0 for fully opaque).