Skip to content

Instantly share code, notes, and snippets.

@Stovoy
Created April 17, 2023 21:17
Show Gist options
  • Save Stovoy/328927128414b1e55559bc854aac2301 to your computer and use it in GitHub Desktop.
Save Stovoy/328927128414b1e55559bc854aac2301 to your computer and use it in GitHub Desktop.
A script to convert an animated webp image to gif
from PIL import Image
def convert_webp_to_gif(webp_file, gif_file):
# Open the WEBP file using the PIL library
webp_image = Image.open(webp_file)
# Initialize lists to store the frames and durations of the WEBP image
frames = []
durations = []
try:
# Loop through each frame of the WEBP image
while True:
# Create a new RGBA image with the same size as the current frame and a transparent background
canvas = Image.new("RGBA", webp_image.size, (0, 0, 0, 0))
# Paste the current frame onto the canvas using the frame itself as the mask
canvas.paste(webp_image.copy(), mask=webp_image)
# Add the processed frame to the frames list
frames.append(canvas)
# Retrieve the duration of the current frame and add it to the durations list
durations.append(webp_image.info['duration'])
# Seek the next frame in the WEBP image
webp_image.seek(len(frames))
except EOFError:
# Break the loop when there are no more frames
pass
# Convert the frames to RGBA and quantize them
gif_frames = [frame.convert("RGBA").quantize(method=2) for frame in frames]
# Check if the image has multiple frames (is an animated GIF)
if len(gif_frames) > 1:
# Save the frames as an animated GIF with the specified durations, loop count, transparency, and disposal method
gif_frames[0].save(gif_file, format='GIF', save_all=True, append_images=gif_frames[1:], loop=0, duration=durations, transparency=0, disposal=2)
else:
# Save the single frame as a GIF with transparency
gif_frames[0].save(gif_file, format='GIF', transparency=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment