# Source - https://stackoverflow.com/a
# Posted by brvoisin
# Retrieved 2025-12-13, License - CC BY-SA 4.0

"""
# 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_image, output_path, max_size):
    frames = list(_thumbnail_frames(input_image, max_size))
    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, max_size):
    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)
