Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 298
jack Avatar asked Dec 26 '09 07:12

jack


People also ask

Do PNG files have alpha?

PNG does not use premultiplied alpha.) Transparency control is also possible without the storage cost of a full alpha channel. In an indexed-color image, an alpha value can be defined for each palette entry. In grayscale and truecolor images, a single pixel value can be identified as being "transparent".

Does PNG support alpha transparency?

PNG files support transparency, but JPGs do not. If you save a PNG image as a JPG file, the JPG format doesn't know what to do with the alpha channel. That's why all the transparency turns into an opaque white background instead.

What is alpha value in image?

In digital images, each pixel contains color information (such as values describing intensity of red, green, and blue) and also contains a value for its opacity known as its 'alpha' value. An alpha value of 1 means totally opaque, and an alpha value of 0 means totally transparent.


2 Answers

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") 
like image 34
Anurag Uniyal Avatar answered Sep 28 '22 14:09

Anurag Uniyal


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.

like image 81
Nadia Alramli Avatar answered Sep 28 '22 12:09

Nadia Alramli