Opening PNG with PIL / Pillow

I am trying to use PIL / Pillow in Python to open a PNG image. You would think that it would be trivial, but the images appear corrupted.

Here is an example image:

I tried downloading it and showing it using Python 3.4 and Pillow 2.7.0:

 $ python Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import PIL.Image >>> image = PIL.Image.open(r'C:\Users\Administrator\Dropbox\Desktop\example.png') >>> image.show() >>> 

What I see is:

Does anyone know why this is and how to solve it? (Corruption occurs not only when I show it, but also when I try to insert it into another image, which is my initial need.)

+7
python image png python-imaging-library pillow
source share
2 answers

As @wiredfool says , the image is converted to RGB before it is displayed. Unfortunately, this means that the alpha channel is simply discarded. You want to make your own transform that mixes the image with a white background.

 Image.composite(image, Image.new('RGB', image.size, 'white'), image).show() 

The documentation for paste shows that it also ignores the alpha channel. You need to specify the image in two places: one for the source and one for the mask.

 base.paste(image, box, image) 
+4
source share

Image.show() writes the image as BMP (in windows), and then opens it using the viewer. Unfortunately, the author of BMP does not save the alpha channel, so you are just viewing the channels of the RGB image.

+3
source share

All Articles