Skip to content

GIF Frame Extractor — Python source

Split an animated GIF into PNG frames with per-frame delays — decoded by our own pure GIF parser, entirely in your browser. Nothing uploads.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""gif-frame-extractor — decode a GIF byte stream into indexed frames.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `gif-frame-extractor` tool, ported
from src/lib/gif-decode.ts.

Why this file exists: a from-scratch GIF87a/89a parser with zero
dependencies — signature + logical screen descriptor (canvas size, global
color table), extension blocks (frame delay, transparency, NETSCAPE loop
count), and LZW image data decompressed to palette indices. Deterministic
and side-effect free; truncated or malformed input returns None.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import List, Optional, Tuple


@dataclass
class GifFrame:
    x: int
    y: int
    width: int
    height: int
    palette: Optional[bytes]  # RGB triplets; None = use global palette.
    indices: bytes  # Pixel indices in natural row order (de-interlaced).
    delay_ms: int  # Frame delay in milliseconds.
    transparent_index: int  # Transparent palette index, or -1.
    disposal: int  # Disposal method 0-7.


@dataclass
class GifResult:
    width: int
    height: int  # Logical screen size.
    frames: List[GifFrame]
    global_palette: Optional[bytes]
    loop_count: float  # NETSCAPE loop; 0 = forever, math.inf when absent.


def lzw_decode(min_code_size: int, data: bytes) -> bytes:
    """GIF LZW decompression — minCodeSize 2-8, clear-code resets, growing codes.

    Codes are read LSB-first across the sub-block payload; the dictionary is
    (prefix, suffix, first-byte) triples reset at every clear code. KwKwK
    (a code one ahead of the dictionary) decodes to prev + first(prev).
    Truncated data stops like browsers do — no exception.
    """
    clear_code = 1 << min_code_size
    eoi_code = clear_code + 1
    code_size = min_code_size + 1
    next_code = eoi_code + 1
    prefix = [-1] * 4096
    suffix = [0] * 4096
    first = [0] * 4096

    def reset_dict() -> None:
        for i in range(clear_code):
            prefix[i] = -1
            suffix[i] = i
            first[i] = i

    reset_dict()

    out = bytearray()

    def emit(code: int) -> int:
        """Emit a code's chain, returning the chain's FIRST byte (for KwKwK)."""
        stack = []
        c = code
        while c >= 0:
            stack.append(suffix[c])
            c = prefix[c]
        out.extend(reversed(stack))
        return stack[-1]

    bit_pos = 0
    prev = -1
    while True:
        # Read one code LSB-first; EOI on truncation, like the TS decoder.
        if (bit_pos + code_size) >> 3 > len(data):
            code = eoi_code
        else:
            code = 0
            for i in range(code_size):
                byte_idx = (bit_pos + i) >> 3
                if byte_idx >= len(data):
                    code = eoi_code
                    break
                code |= ((data[byte_idx] >> ((bit_pos + i) & 7)) & 1) << i
            else:
                bit_pos += code_size
        if code == eoi_code:
            break
        if code == clear_code:
            reset_dict()
            next_code = eoi_code + 1
            code_size = min_code_size + 1
            prev = -1
            continue
        if prev == -1:
            if code >= clear_code:
                break  # First code after clear must be a literal.
            emit(code)
            prev = code
            continue
        if code > next_code:
            break  # Invalid — stop like browsers do.
        # KwKwK: code one ahead of the dictionary decodes to prev + first(prev).
        if code == next_code:
            emit(prev)
            out.append(first[prev])
            emitted_first = first[prev]
        else:
            emitted_first = emit(code)
        if next_code < 4096:  # Table full: TS silently no-ops this write.
            prefix[next_code] = prev
            suffix[next_code] = emitted_first
            first[next_code] = first[prev]
            next_code += 1
            if next_code == (1 << code_size) and code_size < 12:
                code_size += 1
        prev = code
    return bytes(out)


def de_interlace(indices: bytes, width: int, height: int) -> bytes:
    """Reorder interlaced rows into natural order. Identity for short frames."""
    if height < 4 or width == 0:
        return indices
    out = bytearray(len(indices))
    src = 0  # Interlaced data is stored pass-by-pass, four passes.
    for start, step in ((0, 8), (4, 8), (2, 4), (1, 2)):
        for row in range(start, height, step):
            out[row * width:row * width + width] = indices[src:src + width]
            src += width
    return bytes(out)


def decode_gif(data: bytes) -> Optional[GifResult]:
    """Parse signature, screen descriptor, extensions, and all frames.

    Returns None on any truncation, bad magic, or unknown block type — the
    same "malformed input yields null" contract as the TypeScript original.
    """
    if len(data) < 13 or data[:6] not in (b"GIF87a", b"GIF89a"):
        return None
    pos = 6
    width = data[pos] | (data[pos + 1] << 8)
    height = data[pos + 2] | (data[pos + 3] << 8)
    packed = data[pos + 4]
    pos += 7  # Skip bg color + aspect ratio.
    global_palette: Optional[bytes] = None
    if packed & 0x80:
        n = (2 << (packed & 7)) * 3
        if pos + n > len(data):
            return None
        global_palette = data[pos:pos + n]
        pos += n

    frames: List[GifFrame] = []
    loop_count: float = math.inf
    delay_ms = 0
    transparent_index = -1
    disposal = 0

    def read_sub_blocks() -> Optional[bytes]:
        """Concatenate a sub-block chain; None on truncation."""
        nonlocal pos
        chunks: List[bytes] = []
        while True:
            if pos >= len(data):
                return None
            size = data[pos]
            pos += 1
            if size == 0:
                break  # Terminator ends the chain.
            if pos + size > len(data):
                return None
            chunks.append(data[pos:pos + size])
            pos += size
        return b"".join(chunks)

    while True:
        if pos >= len(data):
            return None
        block = data[pos]
        pos += 1
        if block == 0x3B:  # trailer
            break
        if block == 0x21:  # Extension: graphic control / NETSCAPE / skip.
            if pos >= len(data):
                return None
            label = data[pos]
            pos += 1
            if label == 0xF9:
                gce = read_sub_blocks()
                if gce is None or len(gce) < 4:
                    return None
                disposal = (gce[0] >> 2) & 7
                delay_ms = (gce[1] | (gce[2] << 8)) * 10
                transparent_index = gce[3] if gce[0] & 1 else -1
            elif label == 0xFF:
                app = read_sub_blocks()
                # Sub-blocks concatenated: 11-byte name, then id 1 + loop lo/hi.
                if (app is not None and len(app) >= 14
                        and app[:11] == b"NETSCAPE2.0" and app[11] == 1):
                    loop_count = app[12] | (app[13] << 8)
            elif read_sub_blocks() is None:
                return None
            continue
        if block == 0x2C:  # Image descriptor: rect, local palette, LZW data.
            if pos + 9 > len(data):
                return None
            x = data[pos] | (data[pos + 1] << 8)
            y = data[pos + 2] | (data[pos + 3] << 8)
            w = data[pos + 4] | (data[pos + 5] << 8)
            h = data[pos + 6] | (data[pos + 7] << 8)
            ip = data[pos + 8]
            pos += 9  # Descriptor is 9 bytes: x, y, w, h, packed flags.
            palette: Optional[bytes] = None
            if ip & 0x80:
                n = (2 << (ip & 7)) * 3
                if pos + n > len(data):
                    return None
                palette = data[pos:pos + n]
                pos += n
            if pos >= len(data):
                return None
            min_code_size = data[pos]
            pos += 1
            lz = read_sub_blocks()
            if lz is None:
                return None  # LZW payload must be a complete sub-block chain.
            indices = lzw_decode(min_code_size, lz)
            if ip & 0x40:
                indices = de_interlace(indices, w, h)
            frames.append(GifFrame(x, y, w, h, palette, indices,
                                   delay_ms, transparent_index, disposal))
            delay_ms = 0
            transparent_index = -1
            disposal = 0
            continue
        return None  # Unknown block type — bail.
    return GifResult(width, height, frames, global_palette, loop_count)


def _main() -> None:
    # 2×1 GIF89a: 2-color global palette (red, blue), one frame, pixels [0,1].
    gif = (b"GIF89a"
           b"\x02\x00\x01\x00\x80\x00\x00"   # LSD: 2×1, global color table
           b"\xff\x00\x00\x00\x00\xff"       # GCT: red, blue
           b"\x2c\x00\x00\x00\x00\x02\x00\x01\x00\x00"  # image descriptor
           b"\x02\x02\x44\x0a\x00"           # LZW min code size + sub-block
           b"\x3b")                          # trailer
    res = decode_gif(gif)
    if res is None:
        raise SystemExit("malformed GIF")
    loop = res.loop_count if res.loop_count != math.inf else "∞"
    print(f"{res.width}x{res.height}, {len(res.frames)} frame(s), loop={loop}")
    for i, f in enumerate(res.frames):
        print(f"frame {i}: {f.width}x{f.height} at ({f.x},{f.y}), "
              f"delay {f.delay_ms}ms, indices [{', '.join(map(str, f.indices))}]")


if __name__ == "__main__":
    _main()

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →