使用PIL从任何图像中删除透明度/ alpha

Hum*_*rey 9 python alphablending python-imaging-library pillow

如何用指定的背景颜色替换任何图像(png,jpg,rgb,rbga)的alpha通道?它还必须适用于没有Alpha通道的图像.

Hum*_*rey 17

这可以通过检查图像是否透明来完成

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
Run Code Online (Sandbox Code Playgroud)

  • 在现代版本的 Pillow 中,您可能可以使用 `.getchannel('A')` 而不是 `.split()[-1]`。 (4认同)
  • 将图像粘贴到背景上之后,我还必须使用`bg.convert('RGB')`转换为RGB。 (2认同)

Vin*_*s M 10

我建议使用Image.alpha_composite. 如果 png 没有 alpha 通道,
此代码可以避免tuple index out of range错误。

from PIL import Image

png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))

alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
Run Code Online (Sandbox Code Playgroud)

我还建议您使用image.show().

这个答案的功劳归功于 shuuji3和其他人,他们帮助在另一个问题中建立了大量的答案库。