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

后端 未结 5 1184
眼角桃花
眼角桃花 2020-11-30 02:46

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\'
         


        
5条回答
  •  执念已碎
    2020-11-30 03:08

    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")
    

提交回复
热议问题