Remove transparency/alpha from any image using PIL

前端 未结 2 1760
走了就别回头了
走了就别回头了 2020-12-10 13:03

How do I replace the alpha channel of any image (png, jpg, rgb, rbga) with specified background color? It must also work with images that do not have an alpha channel.

2条回答
  •  青春惊慌失措
    2020-12-10 13:39

    This can be done by checking if the image is transparent

    def remove_transparency(im, bg_colour=(255, 255, 255)):
    
        # Only process if image has transparency (http://stackoverflow.com/a/1963146)
        if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
    
            # Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
            alpha = im.convert('RGBA').split()[-1]
    
            # Create a new background image of our matt color.
            # Must be RGBA because paste requires both images have the same format
            # (http://stackoverflow.com/a/8720632  and  http://stackoverflow.com/a/9459208)
            bg = Image.new("RGBA", im.size, bg_colour + (255,))
            bg.paste(im, mask=alpha)
            return bg
    
        else:
            return im
    

提交回复
热议问题