Python – How to get alpha value of a PNG image with PIL

imagepngpythonpython-imaging-librarytransparent

How to detect if a PNG image has transparent alpha channel or not using PIL?

img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'

With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?

I didn't find a 'transparency' key in img.info dictionary as described at PIL's website

I'm using Ubuntu and zlib1g, zlibc packages are already installed.

Best Answer

To get the alpha layer of an RGBA image all you need to do is:

red, green, blue, alpha = img.split()

or

alpha = img.split()[-1]

And there is a method to set the alpha layer:

img.putalpha(alpha)

The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this

if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
    alpha = img.convert('RGBA').split()[-1]

Note: The convert method is needed when the image.mode is LA, because of a bug in PIL.