How to get alpha value of a PNG image with PIL?

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.


You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)

from PIL import Image

imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'

rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)

alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")

The img.info is about the image as a whole -- the alpha-value in an RGBA image is per-pixel, so of course it won't be in img.info. The getpixel method of the image object, given a coordinate as argument, returns a tuple with the values of the (four, in this case) bands for that pixel -- the tuple's last value will then be A, the alpha value.