Inserting legend in images using PIL
I wanted to insert legends directly in images instead of displaying them below respective images. ImageMagick can do that (Text directive) but it's not smart enough to make the legend always visible, even in dark images (if the legend color is black). So i used this script to accomplish that task. Legend is inserted at the bottom of the image, in a little black bordered box. Advice: use pilfonts because default font is a bit small :-)
Here is a sample output:

#. Mike Watkins on Wed Feb 9 19:41:02 2005
ps, converted image to jpg - success; png form of same - failure - although an image is generated. File sizes expand quite a bit, particularly on the png so I presume its the output pre-compression or something like that. Image manipulation is not one of my fortes but I'll keep digging. Thanks for the head start...
#. phil on Thu Feb 10 13:09:36 2005
I only tested the script with jpeg images, i'll try to make it more compatible with other image formats .. And also i need to handle the case where the legend dimensions don't fit in the image.
#. Fredrik on Fri Feb 11 21:05:35 2005
Since you're pasting RGB data on top of the image, the target image has to be an RGB (or RGBA) image as well. GIF always contains 8-bit palette data, JPEG is almost always RGB (and never ever palette data). To make sure you have an RGB image, add
- if image.mode != "RGB":
- image = image.convert("RGB")
to the appropriate place.
(btw, your preview function isn't compatible with IE's popup blockers (neither the built-in variant nor the google bar likes your popup window)).
#. phil on Sat Feb 12 00:06:22 2005
Fredrik,
Thanks for the explanation about RGB.
About popups, i'm not that surprised about IE's popup blocker but can you explain the second part of the note :
neither the built-in variant nor the google bar likes your popup window

#. Mike Watkins on Wed Feb 9 18:55:05 2005
Thanks for your example - I've been meaning to pick up PIL for a drive and this may kickstart me. I fed your script a 441px x 336px GIF image and got this - any suggestions for a first look?Traceback (most recent call last):
File "../test.py", line 80, in ?
annotate(image, text, destination, font)
File "../test.py", line 54, in annotate
inboundBox = Image.blend(inboundBox, textBox, 0.5)
File "/usr/local/lib/python2.4/site-packages/PIL/Image.py", line 1599, in blend
return im1._new(core.blend(im1.im, im2.im, alpha))
ValueError: images do not match