Fitting Transparent 128x128 PNGs Under 128 KB in the Browser: Flood-Fill Keying and Palette Quantization in Canvas 2D
Client-side emoji and sticker pipelines run into a specific browser limitation the moment you need transparency under a strict byte ceiling: HTMLCanvasElement.prototype.toBlob(callback, 'image/png', quality) ignores the quality argument. Unlike image/jpeg or image/webp, the HTML Canvas specification treats image/png as strictly lossless 32-bit RGBA (8 bits per channel). If the encoded output exceeds your target size budget, the browser provides no native encoder knob to dial down compression.
For Slack custom emojis, the hard ingestion limit is 128 KB (131,072 bytes), with square dimensions typically normalized to 128×128 pixels so assets stay sharp at 2× Retina scaling while downsampling cleanly to 22×22 inline text height. A raw 128×128 RGBA buffer contains 16,384 pixels (65,536 uncompressed bytes). Once serialized with PNG chunk headers, scanline filter bytes, and DEFLATE compression, noisy photographic crops, subtle gradients, or feathered alpha masks routinely expand to 45–85 KB—and high-entropy illustrations or noisy background remnants can exceed 128 KB unless pixel entropy is reduced prior to toBlob().
Solving this deterministically in TypeScript without shipping a multi-megabyte WebAssembly codec requires two stages directly on ImageData:
- Corner-seeded BFS flood-fill keying with soft alpha feathering and RGB fringe decontamination, which removes solid or near-solid backdrops without punching holes inside the foreground subject.
- Iterative alpha-preserving quantization with ordered Bayer dithering, which shrinks unique
(R, G, B, A)tuples and increases scanline predictability untilblob.sizefits safely under 128 KB.
Why Global Color Keying Fails on Icons and Avatars
The naive approach to removing a solid background in Canvas 2D iterates linearly over ImageData.data and sets alpha = 0 whenever a pixel's Euclidean RGB distance from a target color falls below a threshold t:
deltaE_RGB = sqrt((R - R_bg)^2 + (G - G_bg)^2 + (B - B_bg)^2) That fails in two predictable ways:
- Interior erosion: A white logo badge or eye highlight on a white background shares the exact same RGB coordinates as the exterior backdrop. Global keying erases interior details along with the outer canvas.
- Hard staircase aliasing and dark halos: Binary alpha (
0or255) leaves jagged 1-pixel stair-steps around curved edges. Conversely, linear alpha ramping across a tolerance band[t, t + f]leaves background RGB values mixed into semi-transparent boundary pixels (C_blended = alpha * C_fg + (1 - alpha) * C_bg). When rendered over a dark UI theme, un-decontaminated white background bleed creates a visible gray fringe.
Algorithm 1: Corner-Seeded BFS Flood-Fill Keying
To isolate only the exterior background, treat the 128×128 raster as a 4-connected grid and seed a breadth-first search (BFS) from the four corners. Pixels enclosed inside foreground contours are never reached.
Using a typed Uint8Array visited bitmask and a preallocated Int32Array queue avoids garbage collection pauses during interactive slider adjustments. Once the exterior mask is resolved, boundary pixels within the feather band [tolerance, tolerance + feather] receive proportional alpha attenuation, and their RGB channels are decontaminated toward neighboring opaque foreground pixels to eliminate backdrop color bleed.
export interface KeyingOptions { tolerance: number; // Core background distance threshold (e.g., 18) feather: number; // Soft edge transition width in RGB units (e.g., 24) } export function keyBackgroundBFS( imageData: ImageData, { tolerance, feather }: KeyingOptions ): ImageData { const { width, height, data } = imageData; const totalPixels = width * height; const visited = new Uint8Array(totalPixels); const queue = new Int32Array(totalPixels); let head = 0; let tail = 0; // Sample top-left corner as reference background color const bgR = data[0]; const bgG = data[1]; const bgB = data[2]; const maxDistSq = (tolerance + feather) ** 2; const enqueue = (idx: number) => { if (!visited[idx]) { visited[idx] = 1; queue[tail++] = idx; } }; // Seed from all four corners enqueue(0); enqueue(width - 1); enqueue((height - 1) * width); enqueue(totalPixels - 1); while (head < tail) { const idx = queue[head++]; const p = idx * 4; const dr = data[p] - bgR; const dg = data[p + 1] - bgG; const db = data[p + 2] - bgB; const distSq = dr * dr + dg * dg + db * db; if (distSq > maxDistSq) continue; const dist = Math.sqrt(distSq); if (dist <= tolerance) { data[p] = 0; data[p + 1] = 0; data[p + 2] = 0; data[p + 3] = 0; } else if (feather > 0) { const alphaRatio = (dist - tolerance) / feather; data[p + 3] = Math.round(data[p + 3] * alphaRatio); // Decontaminate RGB toward opaque neighbor to prevent backdrop halo const x = idx % width; const y = (idx / width) | 0; const neighbors = [ x > 0 ? idx - 1 : -1, x + 1 < width ? idx + 1 : -1, y > 0 ? idx - width : -1, y + 1 < height ? idx + width : -1, ]; for (const nIdx of neighbors) { if (nIdx >= 0 && data[nIdx * 4 + 3] === 255) { const np = nIdx * 4; data[p] = data[np]; data[p + 1] = data[np + 1]; data[p + 2] = data[np + 2]; break; } } } const x = idx % width; const y = (idx / width) | 0; if (x > 0) enqueue(idx - 1); if (x + 1 < width) enqueue(idx + 1); if (y > 0) enqueue(idx - width); if (y + 1 < height) enqueue(idx + width); } return imageData; } Zeroing the RGB channels whenever alpha === 0 is worth calling out explicitly: browsers occasionally retain stale RGB bytes behind fully transparent pixels, and zeroing them collapses every cleared exterior pixel into an identical (0, 0, 0, 0) tuple, dramatically improving PNG DEFLATE run-length matches.
Algorithm 2: Alpha-Preserving Quantization Under a Byte Budget
PNG compression relies on two stages: per-scanline predictive filtering (None, Sub, Up, Average, Paeth) followed by LZ77/Huffman DEFLATE coding. High-frequency sensor noise or smooth 24-bit gradients defeat both stages because adjacent horizontal and vertical pixel residuals remain non-zero and unpredictable.
Even though Canvas toBlob('image/png') always writes a 32-bit RGBA PNG (color_type = 6) rather than an indexed PLTE chunk, reducing the number of discrete amplitude levels per RGB channel forces adjacent residuals to zero and shrinks the LZ77 back-reference dictionary. Applying a lightweight 4×4 ordered Bayer threshold matrix before snapping channels to uniform quantization steps preserves smooth gradients without introducing the spatial dependencies of Floyd-Steinberg error diffusion.
const BAYER_4X4 = [ 0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5, ]; function quantizeWithBayer( source: ImageData, rgbLevels: number, alphaLevels: number ): ImageData { const { width, height, data } = source; const out = new ImageData(new Uint8ClampedArray(data), width, height); const dst = out.data; const rgbStep = 255 / (rgbLevels - 1); const alphaStep = 255 / (alphaLevels - 1); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const p = (y * width + x) * 4; const a = dst[p + 3]; if (a === 0) { dst[p] = dst[p + 1] = dst[p + 2] = 0; continue; } const dither = (BAYER_4X4[(y & 3) * 4 + (x & 3)] / 16 - 0.5) * rgbStep; for (let c = 0; c < 3; c++) { const val = Math.max(0, Math.min(255, dst[p + c] + dither)); dst[p + c] = Math.round(Math.round(val / rgbStep) * rgbStep); } // Keep 255 fully opaque; quantize semi-transparent edge band cleanly if (a < 255) { dst[p + 3] = Math.round(Math.round(a / alphaStep) * alphaStep); } } } return out; } export async function exportUnderByteBudget( canvas: HTMLCanvasElement, baseImage: ImageData, maxBytes = 128 * 1024 ): Promise<Blob> { const ctx = canvas.getContext('2d')!; // Step down RGB levels while keeping 16-level (4-bit) alpha anti-aliasing const schedules: Array<[number, number]> = [ [256, 256], // Lossless pass [64, 32], // 6-bit RGB, 5-bit alpha [32, 16], // 5-bit RGB, 4-bit alpha [16, 16], // 4-bit RGB, 4-bit alpha [8, 8], // 3-bit RGB, 3-bit alpha fallback ]; let lastBlob: Blob | null = null; for (const [rgbLevels, alphaLevels] of schedules) { const frame = rgbLevels === 256 ? baseImage : quantizeWithBayer(baseImage, rgbLevels, alphaLevels); ctx.putImageData(frame, 0, 0); lastBlob = await new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), 'image/png') ); if (lastBlob.size <= maxBytes) return lastBlob; } return lastBlob!; } Keeping a === 255 pinned to 255 and a === 0 pinned to 0 ensures that solid interior regions and cleared exterior regions never pick up dithering noise, restricting quantization strictly to visible color transitions and anti-aliased edge pixels.
Structural Tradeoffs & Visual Verification
In client-side Canvas 2D pipelines, different encoding stages produce distinct structural behaviors depending on source image entropy (such as noisy camera portraits vs. flat vector-style icons):
| Pipeline Stage | Typical 128×128 PNG Size | Color / Alpha Precision | Primary Failure Mode |
|---|---|---|---|
| Raw 128×128 RGBA PNG | 35–85+ KB (can exceed 128 KB with grain/noise) | 8-bit RGB, 8-bit Alpha | Opaque background box; sensor noise inflates DEFLATE stream |
| Corner BFS Keyed RGBA | 18–48 KB | 8-bit RGB, 8-bit Alpha | Un-decontaminated edge RGB causes gray halo on dark themes |
| 5-Bit RGB + Bayer Dither (32 levels) | 10–26 KB | ~5-bit RGB, 4-bit Alpha | Subtle 4×4 crosshatch texture visible only at >200% zoom |
| Indexed 64-Color PNG (WASM/custom encoder) | 6–16 KB | 64 palette entries total | Shared palette slots force harsh alpha stair-stepping on soft edges |
Before finalizing an export, verify the 128×128 PNG at 22×22 CSS pixels (image-rendering: auto) simultaneously over both Light (#FFFFFF) and Dark (#1A1D21) backgrounds. Full-size 128×128 inspection often hides a 1-pixel alpha = 18 background residual, whereas at 22px inline scale, bicubic downsampling averages semi-transparent edge pixels into a noticeable halo against #1A1D21 dark mode surfaces.
Reference Implementation
A live browser-side implementation of this exact 128×128 under-128 KB corner-keyed PNG workflow with dual light/dark inline chat previews is available in the Slack Emoji Maker.
Built while working on browser-side image utilities at Alphaize.