How to Convert an animated transparent WebP to Gif (in Python)?

962 views
Skip to first unread message

Graham Anderson

unread,
Nov 27, 2019, 6:33:30 PM11/27/19
to WebP Discussion
Hello
Is there a pre-built method that converts a transparent webp animation to a Gif?
If not, how do folks on this forum do it?

My first attempt below (using PIL)  screws up the transparency...there must be a better way.
Any push in the right direction is appreciated.

import requests
from io import BytesIO
from PIL import Image

def webp2gif(url, fname):

    # download webp file
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))

    alpha = img.split()[-1]
    img.putalpha(alpha)
    img.info.pop('background', None)

    # the below convert method seems to output a single frame rather than the entire gif
    # perhaps, there is a simple method that converts every gif frame?
    # img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
    img.paste(255, mask)
    img.info['transparency'] = 255

    img.save(f'{fname}.gif', 'gif', save_all=True)
    return img


webp2gif('https://media3.giphy.com/media/i3oszrK5k4NrsQZsqr/giphy.webp?cid=790b76119798e30e4e43b66e9f93f00d0d8f7e6c414a7d0f&rid=giphy.webp',
         'turkey')

xiaoba...@gmail.com

unread,
Jun 17, 2020, 4:40:23 AM6/17/20
to WebP Discussion
from PIL import Image

import requests
from io import BytesIO

#webp to gif convert
#webp link
url = 'https://pic3.zhimg.com/50/v2-c59b4fa2e22001993aa167f618037bb1_hd.webp'
#save image destination
destination = ''


response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.save(destination,'gif',save_all=True)


You can try this.
Reply all
Reply to author
Forward
0 new messages