Skip to content

Instantly share code, notes, and snippets.

@brvoisin
Forked from skywodd/resize_gif.py
Last active September 14, 2022 19:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brvoisin/1ece9083b661bb67bb9d235546b1960a to your computer and use it in GitHub Desktop.
Save brvoisin/1ece9083b661bb67bb9d235546b1960a to your computer and use it in GitHub Desktop.
Resize GIF image using Python Pillow library
"""
# 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