// GIF89a encoder: median-cut quantization (≤256 colors), optional Floyd–Steinberg // dithering, single transparent index when the image has transparent pixels. /** Median-cut palette from RGBA data, refined with a few k-means passes. Returns [[r,g,b], ...]. */ export function medianCutPalette(data, maxColors = 256) { // 15-bit histogram, also accumulating the true channel sums so averages stay exact. const hist = new Uint32Array(32768); const sums = new Float64Array(32768 * 3); const n = data.length / 4; const stride = Math.max(1, Math.floor(n / 250000)); for (let p = 0; p < n; p += stride) { const i = p * 4; if (data[i + 3] < 128) continue; const k = ((data[i] >> 3) << 10) | ((data[i + 1] >> 3) << 5) | (data[i + 2] >> 3); hist[k]++; sums[k * 3] += data[i]; sums[k * 3 + 1] += data[i + 1]; sums[k * 3 + 2] += data[i + 2]; } const bins = []; for (let k = 0; k < 32768; k++) if (hist[k]) bins.push(k); if (!bins.length) return [[0, 0, 0]]; const mean = (k, c) => sums[k * 3 + c] / hist[k]; if (bins.length <= maxColors) return bins.map((k) => [0, 1, 2].map((c) => Math.round(mean(k, c)))); const makeBox = (list) => { const min = [255, 255, 255], max = [0, 0, 0]; let count = 0; for (const k of list) { for (let c = 0; c < 3; c++) { const v = mean(k, c); if (v < min[c]) min[c] = v; if (v > max[c]) max[c] = v; } count += hist[k]; } return { list, min, max, count }; }; const boxes = [makeBox(bins)]; while (boxes.length < maxColors) { // split the box with the largest (range * population) let best = -1, bestScore = 0; for (let i = 0; i < boxes.length; i++) { const b = boxes[i]; if (b.list.length < 2) continue; const range = Math.max(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]); const score = range * Math.sqrt(b.count); if (score > bestScore) { bestScore = score; best = i; } } if (best < 0) break; const b = boxes[best]; const ranges = [0, 1, 2].map((c) => b.max[c] - b.min[c]); const c = ranges.indexOf(Math.max(...ranges)); b.list.sort((x, y) => mean(x, c) - mean(y, c)); let acc = 0, cut = 0; for (; cut < b.list.length - 1; cut++) { acc += hist[b.list[cut]]; if (acc >= b.count / 2) break; } const left = b.list.slice(0, cut + 1), right = b.list.slice(cut + 1); if (!right.length) break; boxes.splice(best, 1, makeBox(left), makeBox(right)); } let palette = boxes.map((b) => { let r = 0, g = 0, bl = 0; for (const k of b.list) { r += sums[k * 3]; g += sums[k * 3 + 1]; bl += sums[k * 3 + 2]; } return [r / b.count, g / b.count, bl / b.count]; }); // k-means refinement over the histogram bins for (let iter = 0; iter < 4; iter++) { const acc = palette.map(() => [0, 0, 0, 0]); for (const k of bins) { const r = mean(k, 0), g = mean(k, 1), b = mean(k, 2); let bi = 0, bd = Infinity; for (let i = 0; i < palette.length; i++) { const p = palette[i]; const d = (p[0] - r) ** 2 * 2 + (p[1] - g) ** 2 * 4 + (p[2] - b) ** 2 * 3; if (d < bd) { bd = d; bi = i; } } const a = acc[bi]; a[0] += sums[k * 3]; a[1] += sums[k * 3 + 1]; a[2] += sums[k * 3 + 2]; a[3] += hist[k]; } palette = palette.map((p, i) => (acc[i][3] ? [acc[i][0] / acc[i][3], acc[i][1] / acc[i][3], acc[i][2] / acc[i][3]] : p)); } return palette.map((p) => p.map((v) => Math.round(v))); } /** Map pixels to palette indices. transparentIndex used for alpha < 128. */ export function mapToPalette(imageData, palette, { dither = true, transparentIndex = -1, offset = 0 } = {}) { const { width: w, height: h, data } = imageData; const out = new Uint8Array(w * h); const cache = new Int16Array(32768).fill(-1); const nearest = (r, g, b) => { const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3); let idx = cache[key]; if (idx >= 0) return idx; let best = 0, bestD = Infinity; for (let i = 0; i < palette.length; i++) { const p = palette[i]; const dr = p[0] - r, dg = p[1] - g, db = p[2] - b; const d = dr * dr * 2 + dg * dg * 4 + db * db * 3; if (d < bestD) { bestD = d; best = i; } } cache[key] = best; return best; }; const err = dither ? new Float32Array(w * h * 3) : null; for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { const p = y * w + x; const i = p * 4; if (data[i + 3] < 128 && transparentIndex >= 0) { out[p] = transparentIndex; continue; } let r = data[i], g = data[i + 1], b = data[i + 2]; if (err) { r = Math.max(0, Math.min(255, r + err[p * 3])); g = Math.max(0, Math.min(255, g + err[p * 3 + 1])); b = Math.max(0, Math.min(255, b + err[p * 3 + 2])); } const idx = nearest(r | 0, g | 0, b | 0); out[p] = idx + offset; if (err) { const c = palette[idx]; const er = r - c[0], eg = g - c[1], eb = b - c[2]; const spread = (q, k) => { err[q * 3] += er * k; err[q * 3 + 1] += eg * k; err[q * 3 + 2] += eb * k; }; if (x + 1 < w) spread(p + 1, 7 / 16); if (y + 1 < h) { if (x > 0) spread(p + w - 1, 3 / 16); spread(p + w, 5 / 16); if (x + 1 < w) spread(p + w + 1, 1 / 16); } } } } return out; } function lzwEncode(indices, minCodeSize) { const bytes = []; let cur = 0, curBits = 0; const emit = (code, size) => { cur |= code << curBits; curBits += size; while (curBits >= 8) { bytes.push(cur & 0xff); cur >>>= 8; curBits -= 8; } }; const clear = 1 << minCodeSize, eoi = clear + 1; let codeSize = minCodeSize + 1; let next = eoi + 1; let table = new Map(); emit(clear, codeSize); let prefix = indices[0]; for (let i = 1; i < indices.length; i++) { const k = indices[i]; const key = (prefix << 8) | k; const found = table.get(key); if (found !== undefined) { prefix = found; continue; } emit(prefix, codeSize); if (next === 4096) { emit(clear, codeSize); next = eoi + 1; codeSize = minCodeSize + 1; table = new Map(); } else { if (next >= (1 << codeSize)) codeSize++; table.set(key, next++); } prefix = k; } emit(prefix, codeSize); emit(eoi, codeSize); if (curBits > 0) bytes.push(cur & 0xff); return bytes; } export function encodeGIF(imageData, { dither = true, colors = 256 } = {}) { const { width: w, height: h, data } = imageData; let hasAlpha = false; for (let i = 3; i < data.length; i += 4) if (data[i] < 128) { hasAlpha = true; break; } const maxColors = Math.max(2, Math.min(256, colors) - (hasAlpha ? 1 : 0)); const palette = medianCutPalette(data, maxColors); const offset = hasAlpha ? 1 : 0; // index 0 = transparent const indices = mapToPalette(imageData, palette, { dither, transparentIndex: hasAlpha ? 0 : -1, offset }); const total = palette.length + offset; let tableBits = 1; while ((1 << tableBits) < total) tableBits++; const tableSize = 1 << tableBits; const minCodeSize = Math.max(2, tableBits); const out = []; const u16 = (v) => out.push(v & 0xff, (v >> 8) & 0xff); for (const c of 'GIF89a') out.push(c.charCodeAt(0)); u16(w); u16(h); out.push(0x80 | 0x70 | (tableBits - 1), 0, 0); for (let i = 0; i < tableSize; i++) { const c = i < offset ? [0, 0, 0] : palette[i - offset] || [0, 0, 0]; out.push(c[0], c[1], c[2]); } if (hasAlpha) out.push(0x21, 0xf9, 0x04, 0x01, 0, 0, 0, 0x00); out.push(0x2c); u16(0); u16(0); u16(w); u16(h); out.push(0); out.push(minCodeSize); const lzw = lzwEncode(indices, minCodeSize); for (let i = 0; i < lzw.length; i += 255) { const chunk = lzw.slice(i, i + 255); out.push(chunk.length, ...chunk); } out.push(0, 0x3b); return new Blob([new Uint8Array(out)], { type: 'image/gif' }); }