GIF Frame Extractor — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* gif-frame-extractor — decode a GIF byte stream into indexed frames.
*
* Language: PHP 7.4+ (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 null. PHP
* strings are raw byte buffers, so ord()/substr() index the GIF stream
* directly, and palette/index payloads travel as binary strings.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/**
* 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.
*/
function lzwDecode(int $minCodeSize, string $data): string
{
$clearCode = 1 << $minCodeSize;
$eoiCode = $clearCode + 1;
$codeSize = $minCodeSize + 1;
$nextCode = $eoiCode + 1;
$prefix = array_fill(0, 4096, -1);
$suffix = array_fill(0, 4096, 0);
$first = array_fill(0, 4096, 0);
$len = strlen($data);
$out = '';
// Emit a code's chain, returning the chain's FIRST byte (for KwKwK).
$emit = function (int $code) use (&$prefix, &$suffix, &$out): int {
$stack = [];
for ($c = $code; $c >= 0; $c = $prefix[$c]) {
$stack[] = $suffix[$c];
}
for ($i = count($stack) - 1; $i >= 0; $i--) {
$out .= chr($stack[$i]);
}
return $stack[count($stack) - 1];
};
$bitPos = 0;
$prev = -1;
while (true) {
// Read one code LSB-first; EOI on truncation, like the TS decoder.
if (($bitPos + $codeSize) >> 3 > $len) {
$code = $eoiCode;
} else {
$code = 0;
$truncated = false;
for ($i = 0; $i < $codeSize; $i++) {
$byteIdx = ($bitPos + $i) >> 3;
if ($byteIdx >= $len) {
$code = $eoiCode;
$truncated = true;
break;
}
$code |= ((ord($data[$byteIdx]) >> (($bitPos + $i) & 7)) & 1) << $i;
}
if (!$truncated) {
$bitPos += $codeSize;
}
}
if ($code === $eoiCode) {
break;
}
if ($code === $clearCode) {
for ($i = 0; $i < $clearCode; $i++) {
$prefix[$i] = -1;
$suffix[$i] = $i;
$first[$i] = $i;
}
$nextCode = $eoiCode + 1;
$codeSize = $minCodeSize + 1;
$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).
if ($code === $nextCode) {
$emit($prev);
$out .= chr($first[$prev]);
$emittedFirst = $first[$prev];
} else {
$emittedFirst = $emit($code);
}
if ($nextCode < 4096) { // Table full: TS silently no-ops this write.
$prefix[$nextCode] = $prev;
$suffix[$nextCode] = $emittedFirst;
$first[$nextCode] = $first[$prev];
$nextCode++;
if ($nextCode === (1 << $codeSize) && $codeSize < 12) {
$codeSize++;
}
}
$prev = $code;
}
return $out;
}
/**
* Reorder interlaced rows into natural order. Identity for short frames.
* Interlaced data is stored pass-by-pass: four passes, starts/steps below.
*/
function deInterlace(string $indices, int $width, int $height): string
{
if ($height < 4 || $width === 0) {
return $indices;
}
$out = str_repeat("\x00", strlen($indices));
$src = 0;
foreach ([[0, 8], [4, 8], [2, 4], [1, 2]] as [$start, $step]) {
for ($row = $start; $row < $height; $row += $step) {
for ($i = 0; $i < $width; $i++) {
$out[$row * $width + $i] = $indices[$src + $i];
}
$src += $width;
}
}
return $out;
}
/**
* Concatenate a sub-block chain; null on truncation. Advances $pos.
*/
function readSubBlocks(string $bytes, int &$pos): ?string
{
$chunks = [];
while (true) {
if ($pos >= strlen($bytes)) {
return null;
}
$size = ord($bytes[$pos++]);
if ($size === 0) {
break; // Terminator ends the chain.
}
if ($pos + $size > strlen($bytes)) {
return null;
}
$chunks[] = substr($bytes, $pos, $size);
$pos += $size;
}
return implode('', $chunks);
}
/**
* Parse a whole GIF: signature, screen descriptor, extensions, all frames.
*
* Returns ['width', 'height', 'frames', 'globalPalette', 'loopCount'] where
* each frame is ['x', 'y', 'width', 'height', 'palette' (RGB triplets or
* null), 'indices' (binary, natural row order), 'delayMs',
* 'transparentIndex' (-1 = none), 'disposal']. loopCount is INF until a
* NETSCAPE2.0 app block sets it (0 = loop forever). Malformed input returns
* null — the same contract as the TypeScript original.
*/
function decodeGif(string $bytes): ?array
{
$len = strlen($bytes);
if ($len < 13) {
return null;
}
$magic = substr($bytes, 0, 6);
if ($magic !== 'GIF87a' && $magic !== 'GIF89a') {
return null;
}
// Logical screen descriptor: canvas size, flags, optional global palette.
$pos = 6;
$width = ord($bytes[$pos]) | (ord($bytes[$pos + 1]) << 8);
$height = ord($bytes[$pos + 2]) | (ord($bytes[$pos + 3]) << 8);
$packed = ord($bytes[$pos + 4]);
$pos += 7; // Skip bg color + aspect ratio.
$globalPalette = null;
if ($packed & 0x80) {
$n = (2 << ($packed & 7)) * 3;
if ($pos + $n > $len) {
return null;
}
$globalPalette = substr($bytes, $pos, $n);
$pos += $n;
}
$frames = [];
$loopCount = INF;
$delayMs = 0;
$transparentIndex = -1;
$disposal = 0;
while (true) {
if ($pos >= $len) {
return null;
}
$block = ord($bytes[$pos++]);
if ($block === 0x3b) {
break; // trailer
}
if ($block === 0x21) { // Extension: graphic control / NETSCAPE / skip.
if ($pos >= $len) {
return null;
}
$label = ord($bytes[$pos++]);
if ($label === 0xf9) {
$gce = readSubBlocks($bytes, $pos);
if ($gce === null || strlen($gce) < 4) {
return null;
}
$disposal = (ord($gce[0]) >> 2) & 7;
$delayMs = (ord($gce[1]) | (ord($gce[2]) << 8)) * 10;
$transparentIndex = ord($gce[0]) & 1 ? ord($gce[3]) : -1;
} elseif ($label === 0xff) {
$app = readSubBlocks($bytes, $pos);
// Sub-blocks concatenated: 11-byte name, then id 1 + loop lo/hi.
if ($app !== null && strlen($app) >= 14
&& substr($app, 0, 11) === 'NETSCAPE2.0' && ord($app[11]) === 1) {
$loopCount = ord($app[12]) | (ord($app[13]) << 8);
}
} elseif (readSubBlocks($bytes, $pos) === null) {
return null;
}
continue;
}
if ($block === 0x2c) { // Image descriptor: rect, local palette, LZW data.
if ($pos + 9 > $len) {
return null;
}
$x = ord($bytes[$pos]) | (ord($bytes[$pos + 1]) << 8);
$y = ord($bytes[$pos + 2]) | (ord($bytes[$pos + 3]) << 8);
$w = ord($bytes[$pos + 4]) | (ord($bytes[$pos + 5]) << 8);
$h = ord($bytes[$pos + 6]) | (ord($bytes[$pos + 7]) << 8);
$ip = ord($bytes[$pos + 8]);
$pos += 9; // Descriptor is 9 bytes: x, y, w, h, packed flags.
$palette = null;
if ($ip & 0x80) {
$n = (2 << ($ip & 7)) * 3;
if ($pos + $n > $len) {
return null;
}
$palette = substr($bytes, $pos, $n);
$pos += $n;
}
if ($pos >= $len) {
return null;
}
$minCodeSize = ord($bytes[$pos++]);
$data = readSubBlocks($bytes, $pos);
if ($data === null) {
return null; // LZW payload must be a complete sub-block chain.
}
$indices = lzwDecode($minCodeSize, $data);
if ($ip & 0x40) {
$indices = deInterlace($indices, $w, $h);
}
$frames[] = ['x' => $x, 'y' => $y, 'width' => $w, 'height' => $h,
'palette' => $palette, 'indices' => $indices, 'delayMs' => $delayMs,
'transparentIndex' => $transparentIndex, 'disposal' => $disposal];
$delayMs = 0;
$transparentIndex = -1;
$disposal = 0;
continue;
}
return null; // Unknown block type — bail.
}
return ['width' => $width, 'height' => $height, 'frames' => $frames,
'globalPalette' => $globalPalette, 'loopCount' => $loopCount];
}
/*
* 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].
* $gif = "GIF89a"
* . "\x02\x00\x01\x00\x80\x00\x00" // LSD: 2×1, GCT
* . "\xff\x00\x00\x00\x00\xff" // GCT: red, blue
* . "\x2c\x00\x00\x00\x00\x02\x00\x01\x00\x00" // image descriptor
* . "\x02\x02\x44\x0a\x00" // LZW + sub-block + term.
* . "\x3b"; // trailer
* $res = decodeGif($gif);
* if ($res === null) { fwrite(STDERR, "malformed GIF\n"); exit(1); }
* $loop = is_infinite($res['loopCount']) ? '∞' : (string) $res['loopCount'];
* printf("%dx%d, %d frame(s), loop=%s\n", $res['width'], $res['height'],
* count($res['frames']), $loop);
* foreach ($res['frames'] as $i => $f) {
* printf("frame %d: %dx%d at (%d,%d), delay %dms, indices [%s]\n", $i,
* $f['width'], $f['height'], $f['x'], $f['y'], $f['delayMs'],
* implode(', ', array_map('ord', str_split($f['indices']))));
* }
*/
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 →