Skip to content

GIF Frame Extractor — JavaScript 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 JavaScript 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: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * 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 null.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/**
 * Parse a whole GIF: signature, screen descriptor, extensions, all frames.
 *
 * Returns `{ width, height, frames, globalPalette, loopCount }` where each
 * frame carries its rect, optional local palette (RGB triplets), pixel
 * indices in natural row order, delay in ms, transparent index (-1 = none)
 * and disposal method. `loopCount` is Infinity until a NETSCAPE2.0 app
 * block sets it (0 = loop forever). Malformed input returns null.
 */
export function decodeGif(bytes) {
  if (bytes.length < 13) return null;
  const magic = String.fromCharCode(...bytes.subarray(0, 6));
  if (magic !== 'GIF87a' && magic !== 'GIF89a') return null;
  // Logical screen descriptor: canvas size, flags, optional global palette.
  let pos = 6;
  const width = bytes[pos] | (bytes[pos + 1] << 8);
  const height = bytes[pos + 2] | (bytes[pos + 3] << 8);
  const packed = bytes[pos + 4];
  pos += 7; // Skip bg color + aspect ratio.
  let globalPalette = null;
  if (packed & 0x80) {
    const entries = 2 << (packed & 7);
    globalPalette = bytes.slice(pos, pos + entries * 3);
    if (globalPalette.length < entries * 3) return null;
    pos += entries * 3;
  }

  const frames = [];
  let loopCount = Infinity, delayMs = 0, transparentIndex = -1, disposal = 0;

  /** Concatenate a sub-block chain; null on truncation. */
  const readSubBlocks = () => {
    const chunks = [];
    for (;;) {
      if (pos >= bytes.length) return null;
      const size = bytes[pos++];
      if (size === 0) break; // Terminator ends the chain.
      if (pos + size > bytes.length) return null;
      chunks.push(bytes.subarray(pos, pos + size));
      pos += size;
    }
    const out = new Uint8Array(chunks.reduce((s, c) => s + c.length, 0));
    let o = 0;
    for (const c of chunks) { out.set(c, o); o += c.length; }
    return out;
  };

  for (;;) {
    if (pos >= bytes.length) return null;
    const block = bytes[pos++];
    if (block === 0x3b) break; // trailer
    if (block === 0x21) { // Extension: graphic control / NETSCAPE / skip.
      if (pos >= bytes.length) return null;
      const label = bytes[pos++];
      if (label === 0xf9) {
        const gce = readSubBlocks();
        if (!gce || gce.length < 4) return null;
        disposal = (gce[0] >> 2) & 7;
        delayMs = (gce[1] | (gce[2] << 8)) * 10;
        transparentIndex = gce[0] & 1 ? gce[3] : -1;
      } else if (label === 0xff) {
        const app = readSubBlocks();
        // Sub-blocks concatenated: 11-byte name, then id 1 + loop lo/hi.
        if (app && app.length >= 14 &&
            String.fromCharCode(...app.subarray(0, 11)) === 'NETSCAPE2.0' && app[11] === 1) {
          loopCount = app[12] | (app[13] << 8);
        }
      } else if (!readSubBlocks()) return null;
      continue;
    }
    if (block === 0x2c) { // Image descriptor: rect, local palette, LZW data.
      if (pos + 9 > bytes.length) return null;
      const x = bytes[pos] | (bytes[pos + 1] << 8);
      const y = bytes[pos + 2] | (bytes[pos + 3] << 8);
      const w = bytes[pos + 4] | (bytes[pos + 5] << 8);
      const h = bytes[pos + 6] | (bytes[pos + 7] << 8);
      const ip = bytes[pos + 8];
      pos += 9; // Descriptor is 9 bytes: x, y, w, h, packed flags.
      let palette = null;
      if (ip & 0x80) {
        const entries = 2 << (ip & 7);
        palette = bytes.slice(pos, pos + entries * 3);
        if (palette.length < entries * 3) return null;
        pos += entries * 3;
      }
      if (pos >= bytes.length) return null;
      const minCodeSize = bytes[pos++];
      const data = readSubBlocks();
      if (!data) return null; // LZW payload must be a complete sub-block chain.
      const indices = lzwDecode(minCodeSize, data);
      const final = ip & 0x40 ? deInterlace(indices, w, h) : indices;
      frames.push({ x, y, width: w, height: h, palette, indices: final,
        delayMs, transparentIndex, disposal });
      delayMs = 0; transparentIndex = -1; disposal = 0;
      continue;
    }
    return null; // Unknown block type — bail.
  }
  return { width, height, frames, globalPalette, loopCount };
}

/** Reorder interlaced rows into natural order. Identity for short frames. */
export function deInterlace(indices, width, height) {
  if (height < 4 || width === 0) return indices;
  const out = new Uint8Array(indices.length);
  let src = 0; // Interlaced data is stored pass-by-pass, four passes.
  for (const [start, step] of [[0, 8], [4, 8], [2, 4], [1, 2]]) {
    for (let row = start; row < height; row += step) {
      out.set(indices.subarray(src, src + width), row * width);
      src += width;
    }
  }
  return out;
}

/**
 * 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 throw.
 */
export function lzwDecode(minCodeSize, data) {
  const clearCode = 1 << minCodeSize, eoiCode = clearCode + 1;
  let codeSize = minCodeSize + 1, nextCode = eoiCode + 1;
  const prefix = new Int32Array(4096), suffix = new Uint8Array(4096), first = new Uint8Array(4096);
  const resetDict = () => {
    for (let i = 0; i < clearCode; i++) { prefix[i] = -1; suffix[i] = i; first[i] = i; }
    nextCode = eoiCode + 1; codeSize = minCodeSize + 1;
  };
  resetDict();
  const out = [];
  /** Emit a code's chain, returning the chain's FIRST byte (for KwKwK). */
  const emit = (code) => {
    const stack = []; let c = code;
    while (c >= 0) { stack.push(suffix[c]); c = prefix[c]; }
    for (let i = stack.length - 1; i >= 0; i--) out.push(stack[i]);
    return stack[stack.length - 1];
  };
  let bitPos = 0, prev = -1;
  for (;;) {
    // Read one code LSB-first; EOI on truncation, like the TS decoder.
    let code;
    if ((bitPos + codeSize) >> 3 > data.length) { code = eoiCode; }
    else {
      code = 0;
      let truncated = false;
      for (let i = 0; i < codeSize; i++) {
        const byteIdx = (bitPos + i) >> 3;
        if (byteIdx >= data.length) { code = eoiCode; truncated = true; break; }
        code |= ((data[byteIdx] >> ((bitPos + i) & 7)) & 1) << i;
      }
      if (!truncated) bitPos += codeSize;
    }
    if (code === eoiCode) break;
    if (code === clearCode) { resetDict(); prev = -1; continue; }
    if (prev === -1) {
      if (code >= clearCode) break; // First code after clear must be a literal.
      emit(code); prev = code; continue;
    }
    if (code > nextCode) break; // Invalid — stop like browsers do.
    // KwKwK: code one ahead of the dictionary decodes to prev + first(prev).
    const emittedFirst = code === nextCode ? (emit(prev), out.push(first[prev]), first[prev]) : emit(code);
    prefix[nextCode] = prev; suffix[nextCode] = emittedFirst; first[nextCode] = first[prev];
    nextCode++; prev = code;
    if (nextCode === 1 << codeSize && codeSize < 12) codeSize++;
  }
  return Uint8Array.from(out);
}

// ---- Example usage (this file is a library; uncomment to run as a script) ---
// // 2×1 GIF89a: 2-color global palette (red, blue), one frame, pixels [0,1].
// const gif = new Uint8Array([
//   ...'GIF89a'.split('').map((c) => c.charCodeAt(0)),
//   0x02, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, // LSD: 2×1, GCT
//   0xff, 0x00, 0x00, 0x00, 0x00, 0xff,       // GCT: red, blue
//   0x2c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00,
//   0x02, 0x02, 0x44, 0x0a, 0x00, 0x3b,       // LZW + sub-block + trailer
// ]);
// const res = decodeGif(gif);
// console.log(`${res.width}x${res.height}, ${res.frames.length} frame(s), loop=${res.loopCount}`);
// console.log(res.frames[0].indices); // Uint8Array(2) [0, 1]

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 →