Retrieve a GIF's palette entries using Python Imaging Library (PIL)

and-google at doxdesk.com and-google at doxdesk.com
Thu Jan 19 05:51:02 EST 2006


Stuart wrote:

> I see that the 'Image' class has a 'palette' attribute which returns an
> object of type 'ImagePalette'.  However, the documentation is a bit
> lacking regarding how to maniuplate the ImagePalette class to retrieve
> the palette entries' RGB values.

ImagePalette.getdata() should do it.

There seems to be some kind of bug, however, where Images lose their
ImagePalettes after being convert()ed to paletted images (eg. using
Image.ADAPTIVE). For this reason I personally use the getpalette()
method from the wrapped image object, which seems to contain the proper
raw palette data. For example to get a list of [r,g,b] colour lists:

  def chunk(seq, size):
    return [seq[i:i+size] for i in range(0, len(seq), size)]

  palette= image.im.getpalette()
  colours= [map(ord, bytes) for bytes in chunk(palette, 3)]

-- 
And Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/




More information about the Python-list mailing list