[PYTHON IMAGE-SIG] PIL and palettes and drawing.

Fredrik Lundh fredrik_lundh@ivab.se
Tue, 17 Dec 1996 10:49:52 +0100

> How do I initialise a colour palette? In particular, I'm trying to use
> ImageDraw, with a new image object, and I need to know how to drive the
> constructor &c for the palette.
> im=Image.new("P",(400,400))
> im.palette=ImagePalette.ImagePalette("RGB")

Hmm.  You've stumbled upon something that have been on my TODO list a
long time...

The ImagePalette module doesn't work as it should, so it really takes
some magic to do what you need:

	image = Image.new("P",(400,400))

	# create a list to hold the palette
	palette = [(0,0,0)] * 256

	# set an entry
	palette[1] = (255, 0, 0)
	palette[255] = (255, 255, 255)

	# convert the list to a string
	palette = map(lambda a: chr(a[0])+chr(a[1])+chr(a[2]), palette)
	palette = string.join(palette, "")

	# attach it to the image	
	image.im.putpalette("RGB", palette)

Note that its "image.im", not just "image".  See WmfImagePlugin.py for
some variations of this theme.

(And yes, now that ImageDraw is getting quite useful, I'd better fix
the palette module).

Cheers	/F

IMAGE-SIG - SIG on Image Processing with Python

send messages to: image-sig@python.org
administrivia to: image-sig-request@python.org