I’ve read alot of threads (and experienced first hand) many issues with annotating text on top of an image. ImageMagick is a great versatile tool, but its text handling can leave you a bit frazzled at times. For example, I have yet to see sample code demonstrating switching fonts (or even just font parameters like bold & italic) midway through a sentence.
The traditional approach is to pass multiple annotate commands through to ImageMagick and deal with it that way. The problem is that you have to keep track of where you are on the image yourself for successive annotate calls. Otherwise what happens is that you end up overwriting what you just printed and create a big mess.
An even bigger problem occurs when you try to do wrapping. All of a sudden you’re responsible for checking every word to see if it goes outside your bounding box, and then linefeeding intelligently if it does. Sounds alot like the job for a typesetter, right?
Well, I found a nice little approach that does the job and spits out a beautiful annotated image within ImageMagick. All it takes is Perl, a module called PostScript::BasicTypesetter and of course your fonts!
Here is my sample Perl code:
use PostScript::BasicTypesetter;
my $fontsize = 15;
my $lineheight = 16;
my $currentline = 1;
my $r = new PostScript::BasicTypesetter(”fg2/FrankGB2.afm”); #FranklinGothic-Book
$r->fontsize($fontsize,$lineheight);
my $bi = new PostScript::BasicTypesetter(”fg2/FranGDOw.afm”); #FranklinGothic-DemiOblique
$bi->fontsize($fontsize,$lineheight);
my $b = new PostScript::BasicTypesetter(”fg2/FrankGDq.afm”); #FranklinGothic-Demi
$b->fontsize($fontsize,$lineheight);
my $i= new PostScript::BasicTypesetter(”fg2/FranGBO0.afm”); #FranklinGothic-BookOblique
$i->fontsize($fontsize,$lineheight);
my $ps = new PostScript::BasicTypesetter(”fg2/FrankGB2.afm”);
$ps->fontsize($fontsize,$lineheight);
$ps->ps_setcolor([0,0,0]);
print STDOUT (”%!PS-Adobe-3.0\n”,
“%%DocumentResources: font “,
$ps->metrics->FontName, ” “,
“%%Pages: 1\n”,
$ps->ps_preamble,
“%%EndPrologue\n”,
“%%Page 1 1\n”);
print STDOUT “%%DocumentMedia: Default 300 150 0 () ()\n”;
my @arr = ($r,’This is a nice chunk of text with ‘,$b,’bold, ‘,$i,’Italics’,$bi,’, and both at once!’);
my $x = 50;
my $xi = 0;
my $y = 100;
my $w = 200;
print STDOUT ($ps->ps_textbox ($x, $xi, $y, $w,\@arr, “l”));
print STDOUT (”showpage\n”,
“%%Trailer\n”,
“%%EOF\n”);
What this code produces is straight postscript data. Not too appealing on its own. However if you pipe the output in to ImageMagick, you get perfectly formatted and wrapped text:
perl textwrap.pl | convert - test.jpg
Produces the following image:

Very useful for realtime wrapping previews!