Skip to content
Advertisement

Converting Webp to JPG with a white background using Pillow

My code is giving me each time a new error, I just want to convert a Webp image to JPG with a white background

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)

Advertisement

Answer

You can do it most simply like this:

#!/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')

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement