[Image-SIG] PNG transparency not recognized

Fredrik Lundh fredrik at pythonware.com
Wed Aug 13 13:35:07 CEST 2008


Sebastian Spaeth wrote:

> extensive googling didn't help, so here I go. I produce PNG files with lot's of transparency. These are run through various PNG optimizers (pngnq, pngcrush).
> 
> When I try to open them, they are im.mode='RGB', ie all the transparency is gone. This is the same in PIL 1.1.5 and 1.1.6.
> 
> Example PNG here: http://sspaeth.de/pyblosxom/caption_6_33_22.png
> Try to open that in Gimp and you'll see the transparent background. Open in PIL and there's no transparency. Or have I overlooked something?

PIL doesn't support images using a "transparency color index", but many 
file codecs does at least add the color to the info dictionary, usually 
under the "transparency" key.

For some reason, the PNG codec doesn't do this for RGB images.

I've attached a simple patch that fixes the reader; with this in place, 
you can get the background color as im.info["transparency"]:

 >>> from PIL import Image
 >>> im = Image.open('caption_6_33_22.png')
 >>> im.info
{'transparency': (248, 248, 248)}

</F>

Index: PIL/PngImagePlugin.py
===================================================================
--- PIL/PngImagePlugin.py       (revision 3404)
+++ PIL/PngImagePlugin.py       (working copy)
@@ -220,6 +220,8 @@
                  self.im_info["transparency"] = i
          elif self.im_mode == "L":
              self.im_info["transparency"] = i16(s)
+        elif self.im_mode == "RGB":
+            self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:])
          return s

      def chunk_gAMA(self, pos, len):



More information about the Image-SIG mailing list