Skip to content

Instantly share code, notes, and snippets.

@nimatrueway
Forked from Nua07/python_pillow_webp2gif.py
Last active February 19, 2023 19:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nimatrueway/0e743d92056e2c5f995e25b848a1bdcd to your computer and use it in GitHub Desktop.
Save nimatrueway/0e743d92056e2c5f995e25b848a1bdcd to your computer and use it in GitHub Desktop.
Convert webp animations to gif preserving image quality (RGB = 24bit)
#!/usr/bin/env python3
from sys import argv
from pathlib import Path
from PIL import Image, ImageSequence
def webp2gif(path: Path):
img = Image.open(path)
frames: list[Image.Image] = []
for frame in ImageSequence.Iterator(img):
im2 = Image.new("RGB", frame.size, (255, 255, 255))
bands = frame.split()
mask = bands[3] if len(bands)>3 else None
im2.paste(frame, mask=mask)
frames.append(im2.convert('RGB'))
frames[0].save(path.with_suffix('.gif'),
format='gif',
save_all=True,
append_images=frames[1:],
optimize=True,
duration=img.info.get("duration", 10),
loop=img.info.get("loop", 0),
quality=100)
webp2gif(Path(argv[1]))
@Vanawy
Copy link

Vanawy commented Feb 9, 2022

Thank you!

@reviveMC74
Copy link

I suggest replacing line 13 (im2.paste(frame, mask=frame.split()[3])) with these 3 lines:

bands = frame.split()
mask = bands[3] if len(bands)>3 else None
im2.paste(frame, mask=mask)

If the .webp contains only R, G, B and no A (opacity) bands, there are only 3 bands, so 'frame.split()[3]' causes an exception.

Thanks for the example.

@WebLeach
Copy link

@reviveMC74 thanksss i was stuck here

@nimatrueway
Copy link
Author

I suggest replacing line 13 (im2.paste(frame, mask=frame.split()[3])) with these 3 lines:

bands = frame.split()
mask = bands[3] if len(bands)>3 else None
im2.paste(frame, mask=mask)

If the .webp contains only R, G, B and no A (opacity) bands, there are only 3 bands, so 'frame.split()[3]' causes an exception.

Thanks for the example.

Thanks, applied.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment