使用 Pillow 将 Webp 转换为白色背景的 JPG

Converting Webp to JPG with a white background using Pillow

我的代码每次都会出现新错误,我只想将 Webp 图片转换为白色背景的 JPG

from PIL import Image
import os

for webbp in os.listdir("."):
    if webbp.endswith(r'.webp'):
        jpgsname = webbp.replace('.webp', '') + ".jpg"
        print(webbp)
        im = Image.open("./" + webbp).convert("RGBA")
        non_transparent=Image.new('RGBA',im.size,(255,255,255,255))
        non_transparent.paste(im,(0,0),im)
        non_transparent.convert("RGB")
        non_transparent.save(jpgsname)
        os.chdir(".")
        print("Converted " + jpgsname)
        os.remove(webbp)

你可以像这样最简单地做到这一点:

#!/usr/bin/env python3

from PIL import Image

# Open webp image with alpha
im = Image.open('webp-lossless-with-alpha.webp')

# Make same size white background to paste it onto
bg = Image.new('RGB', im.size, 'white')

# Paste the webp with alpha onto the white background
bg.paste(im, im)
bg.save('result.jpg')