PythonIntermediate · Windows, macOS, or Linux with Python 3.12+

Extract the rendered frames of a GIF

Save GIF frames as composited PNG images plus their durations.

Before you begin

  • Python 3.12 or newer
  • Pillow installed in the same Python environment
What this script changesCreates new image files or a new frame directory. Inputs and outputs are limited to 20 million pixels per image; animated tasks also cap frame count. Ordinary transforms process the first frame and normalize EXIF orientation. Color profiles and original metadata are not preserved reliably; use source copies for archival work.

Set up your example

  1. Save the complete code as image-gif-frames.py in a working folder.
  2. Save the provided sample files in that same folder; run commands from that folder.
  3. Install Pillow: python -m pip install Pillow
  4. Generate the original fixtures once: python "make_samples.py". Choose an empty folder so the fixture files do not exist.

Sample files in this download:

  • make_samples.py

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is image-gif-frames.py.

Run the script

Run command
python "image-gif-frames.py" --input "sample.gif" --output "frames"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

Save GIF frames as composited PNG images plus their durations. The two-frame fixture creates frame_0000.png, frame_0001.png, and timing.json.

The complete script

image-gif-frames.py
#!/usr/bin/env python3
'Extract the rendered frames of a GIF'
import argparse
import json
from pathlib import Path

def write_json(path, value):
    data = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    with Path(path).open("x", encoding="utf-8", newline="") as handle:
        handle.write(data)

import math

try:
    from PIL import Image, ImageOps, ImageEnhance, ImageFilter, ImageDraw, ImageFont, ImageChops
except ImportError:
    raise SystemExit("Install Pillow first: python -m pip install Pillow")
MAX_PIXELS=20_000_000
def check_size(size):
    if min(size)<1 or size[0]*size[1]>MAX_PIXELS:
        raise ValueError("Image dimensions must be positive and at most 20 million pixels.")
def read_image(path):
    with Image.open(path) as original:
        check_size(original.size)
        return ImageOps.exif_transpose(original).convert("RGBA")
def save_image(path,image,format="PNG"):
    check_size(image.size)
    with Path(path).open("xb") as handle:
        image.save(handle,format=format)

def main():
    parser = argparse.ArgumentParser(description='Extract the rendered frames of a GIF')
    parser.add_argument("--input",required=True,help="Local source image")
    parser.add_argument("--output",required=True,help="New output file or directory")
    parser.add_argument("--max-frames",type=int,default=100)
    args = parser.parse_args()
    if not 1<=args.max_frames<=100: raise ValueError("Max frames must be 1..100.")
    with Image.open(args.input) as animation:
        check_size(animation.size)
        if animation.format!="GIF": raise ValueError("Expected a GIF image.")
        count=getattr(animation,"n_frames",1)
        if count>args.max_frames: raise ValueError("Frame count exceeds the limit.")
        folder=Path(args.output)
        folder.mkdir()
        timing=[]
        for i in range(count):
            animation.seek(i)
            save_image(folder/f"frame_{i:04d}.png",animation.convert("RGBA"))
            timing.append({"frame":i,"milliseconds":animation.info.get("duration",0)})
        write_json(folder/"timing.json",timing)

if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, TypeError, ArithmeticError, IndexError, LookupError) as exc:
        raise SystemExit(str(exc))

Open source as plain text · Download source and sample files

How it works

  1. Pillow reads the local image; the source is left unchanged and existing destinations are refused.
  2. Pillow applies GIF disposal while seeking, so outputs represent rendered frames rather than raw incremental rectangles.
  3. The two-frame fixture creates frame_0000.png, frame_0001.png, and timing.json.

Make it your own

--max-frames

Lower --max-frames when handling unknown animations.

Adapt the processing

Edit main's timing records to include the animation loop value.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

The frame directory already exists.

Choose a new directory; an interrupted extraction can leave a partial result.

The destination already exists.

Choose a new --output path. The script deliberately refuses to replace an existing result.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.