Transparent GIFs in PIL

Steve Purcell stephen_purcell at yahoo.com
Thu Mar 22 12:01:10 EST 2001


Marcos Sánchez Provencio wrote:
> Is it possible to set a transparent color in a GIF file (originally not
> transparent) in PIL?
> 

With PIL 1.0, not directly. For later versions (if they exist), I don't know.

You can patch the PIL 1.0 version of 'GifImagePlugin.py' as follows:

############
--- GifImagePlugin.py   Thu May  4 11:15:49 2000
+++ /tmp/GifImagePlugin.py      Thu Mar 22 17:57:43 2001
@@ -303,6 +303,12 @@
        for i in range(256):
            s.append(chr(i) * 3)
 
+    # save transparency
+    if im.info.has_key('transparency'):
+        transparentIndex = im.info['transparency']
+        s.append('!' + chr(0xf9) + chr(4) + chr(1) + chr(0) + chr(0) +
+                 chr(transparentIndex) + chr(0))
+
     return s
 
 def getdata(im, offset = (0, 0), **params):
############


Then, if you know the index of the colour in the GIF's palette you can say:

   >> image = Image.open('my.gif')
   >> transparent_colour_index = 4
   >> image.info['transparency'] = transparent_colour_index
   >> image.save('my_transparent.gif')


-Steve


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list