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

后端 未结 5 1183
眼角桃花
眼角桃花 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:11

    # python 2.6+
    
    import operator, itertools
    
    def get_alpha_channel(image):
        "Return the alpha channel as a sequence of values"
    
        # first, which band is the alpha channel?
        try:
            alpha_index= image.getbands().index('A')
        except ValueError:
            return None # no alpha channel, presumably
    
        alpha_getter= operator.itemgetter(alpha_index)
        return itertools.imap(alpha_getter, image.getdata())
    

提交回复
热议问题