-
-
Save brvoisin/1ece9083b661bb67bb9d235546b1960a to your computer and use it in GitHub Desktop.
Resize GIF image using Python Pillow library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
# Resize an animated GIF | |
Inspired from https://gist.github.com/skywodd/8b68bd9c7af048afcedcea3fb1807966 | |
Useful links: | |
* https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#saving | |
* https://stackoverflow.com/a/69850807 | |
Example: | |
``` | |
python resize_gif.py input.gif output.gif 400,300 | |
``` | |
""" | |
import sys | |
from PIL import Image | |
from PIL import ImageSequence | |
def resize_gif(input_path, output_path, max_size): | |
input_image = Image.open(input_path) | |
frames = list(_thumbnail_frames(input_image)) | |
output_image = frames[0] | |
output_image.save( | |
output_path, | |
save_all=True, | |
append_images=frames[1:], | |
disposal=input_image.disposal_method, | |
**input_image.info, | |
) | |
def _thumbnail_frames(image): | |
for frame in ImageSequence.Iterator(image): | |
new_frame = frame.copy() | |
new_frame.thumbnail(max_size, Image.Resampling.LANCZOS) | |
yield new_frame | |
if __name__ == "__main__": | |
max_size = [int(px) for px in sys.argv[3].split(",")] # "150,100" -> (150, 100) | |
resize_gif(sys.argv[1], sys.argv[2], max_size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment