Remove transparency/alpha from any image using PIL

前端 未结 2 1757
走了就别回头了
走了就别回头了 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:42

    I'd suggest using Image.alpha_composite.
    This code can avoid a tuple index out of range error if png has no alpha channel.

    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)
    

    I also recommend you inspect both results with a image.show().

    Credits for this answer goes to shuuji3 and others who helped build a vast answers repertoire in this other question.

提交回复
热议问题