Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 7 min read

Compressing GIFs to an exact file size in the browser with WebAssembly

A Discord emoji must be under 256 KB. A Slack emoji, under 128 KB. A Discord upload on a free account, under 10 MB. Most GIFs people want to use are several megabytes, and most online compressors ask you to upload the fi

A Discord emoji must be under 256 KB. A Slack emoji, under 128 KB. A Discord upload on a free account, under 10 MB. Most GIFs people want to use are several megabytes, and most online compressors ask you to upload the file to their server first, then hand you back one fixed result.

We wanted something different: tell the tool the number, and get the best-looking GIF that fits β€” without the file ever leaving the device. That became GifSmaller, a static site where all the work happens in the browser.

This post covers the three parts that took the most thought:

  1. Running gifsicle, a C program, in a Web Worker through WebAssembly β€” and the Content Security Policy line that made it hang without an error.
  2. A search that finds the gentlest settings that still fit a byte budget, in at most 16 encoder runs.
  3. Cropping every frame of an animated GIF, plus two bugs an automated code review caught before they shipped.

Running gifsicle in a Web Worker

gifsicle has been the reference GIF optimizer for decades. Its -O3 optimizer stores only the pixels that change between frames, and its --lossy option (from the giflossy fork, now merged) trades a little noise for much better LZW compression. Rewriting that in JavaScript would be slower and worse, so we use a WebAssembly build of gifsicle 1.92 from the gifsicle-wasm-browser package.

The package ships a worker script and embeds the .wasm as a data: URL. We load it lazily β€” it is about 150 KB gzipped β€” and start the download as soon as someone hovers the drop zone or drags a file over the page:

let workerUrlPromise: Promise<string> | null = null;

function loadWorkerUrl(): Promise<string> {
  workerUrlPromise ??= import('gifsicle-wasm-browser').then((m) => m.default.tool.worker());
  return workerUrlPromise;
}

Each encode is one gifsicle command line. Options map directly to flags, and anything that is a no-op is left out:

export function buildCommand(o: EncodeOptions, inputName = 'in.gif'): string {
  const parts = ['-O3', '--no-warnings'];
  if (o.lossy > 0) parts.push(`--lossy=${Math.round(o.lossy)}`);
  if (o.colors < 256) parts.push(`--colors=${Math.max(2, Math.round(o.colors))}`);
  if (o.scale < 1) parts.push(`--scale=${o.scale.toFixed(4)}`);
  if (o.crop) {
    const { x, y, width, height } = o.crop;
    parts.push(`--crop=${x},${y}+${width}x${height}`); // applies to the input after it
  }
  parts.push(inputName, '-o', '/out/out.gif');
  return parts.join(' ');
}

The CSP line that made it hang

The first deploy worked locally and froze in production: the UI said β€œCompressing…” forever, with no error in the console. The worker is created from a blob: URL and fetches its WebAssembly from a data: URL, and our Content Security Policy allowed the first but not the second. The fetch failed inside the worker, and the worker simply never answered.

The policy now carries all three things the engine needs:

script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; connect-src 'self' data:

We also stopped trusting the worker to always reply. Every run has a three-minute watchdog; on timeout, error or cancel the worker is terminated and the next encode starts a fresh one. That turned a silent hang into an error message, which is the difference between a bug report and a user who just leaves.

Searching for a target size

gifsicle has no β€œmake it 256 KB” flag, so the tool has to search. Every encode of a multi-megabyte GIF takes from a fraction of a second to several seconds, so the search has to be frugal. We order the options by how much they hurt the picture:

  1. Lossless first. -O3 alone often saves 10–40% with no visible change. If that fits, stop.
  2. Lossy at full size. Try the strongest level, --lossy=200. If even that is too big, lossy alone can’t do it β€” go to step 3. If it fits, binary-search for the gentlest level that still fits.
  3. Smaller dimensions, last. Shrink the scale and repeat step 2.

The binary search keeps a bracket β€” hi is a level known to fit, lo one known (or assumed) not to β€” and stops when the bracket is 15 levels wide, because the visual difference between --lossy=80 and --lossy=95 is not worth another encode:

let lo = 0; // too big
let hi = LOSSY_MAX; // fits
while (hi - lo > LOSSY_TOLERANCE && attempts.length < maxRuns) {
  const mid = Math.round((lo + hi) / 2);
  const bytes = await run({ lossy: mid, colors: 256, scale });
  if (bytes.length <= target) {
    hi = mid;
    best = { bytes, options: { lossy: mid, colors: 256, scale } };
  } else {
    lo = mid;
  }
}

When the strongest lossy level is still too big, we shrink. File size grows roughly with pixel area, so the scale factor comes from the square root of how far over budget we are, with an 8% margin and sensible bounds:

const factor = Math.min(0.9, Math.max(0.25, Math.sqrt(target / strongBytes.length) * 0.92));
scale *= factor;

The whole search is capped at 16 encoder runs. If the target is unreachable β€” a 30-second, 1080p recording will never be 100 KB at a useful size β€” it returns the smallest output it found and says so, instead of quietly handing back something over the limit.

Presets add one shortcut. Discord shows emoji at up to 128 px, so the Discord emoji goal caps the longest side at 128 px before the first run; there is no point spending encodes on pixels nobody will see.

On a 480 Γ— 360, 36-frame test GIF of 2.25 MB:

Goal Result Size
Balanced (one pass, --lossy=60) 480 Γ— 360, 36 frames 880 KB (61% smaller)
Discord emoji (≀ 256 KB, 128 px) 128 Γ— 96, 36 frames 228 KB (90% smaller)

Because the encoder is passed in as a function, the search itself is a pure function. The unit tests drive it with a fake encoder that models size from the options β€” no WebAssembly, no worker, and every branch (fits losslessly, fits after the binary search, needs shrinking, unreachable) runs in milliseconds.

Cropping every frame

Cropping an animated GIF in an ordinary image editor usually gives you a still image, because the editor only reads the first frame. gifsicle crops every frame with --crop=X,Y+WxH, including frames that only cover part of the canvas. One detail matters: the option applies to the input files that come after it on the command line, so it has to sit before in.gif.

The interactive part is a crop box over the animated preview. The box is positioned in percentages of the image, so it stays correct when the preview is scaled down on a phone, and all the geometry β€” moving, resizing from one of eight handles, locking an aspect ratio, applying a typed value β€” lives in small pure functions in source-pixel space. The component only turns pointer deltas into source pixels and calls them:

const dx = (e.clientX - start.x) * (img.width / stage.clientWidth);
const dy = (e.clientY - start.y) * (img.width / stage.clientWidth);
setRect(mode === 'move' ? moveRect(startRect, dx, dy, img) : resizeRect(startRect, mode, dx, dy, img, ratio));

Pointer capture on the handle keeps the drag going when the finger leaves it, which is what makes the same code work with a mouse and on a touch screen.

Two bugs a code review caught

Our pull requests get an automated review, and on the cropper it found two real bugs that our tests had missed:

  • The aspect ratio broke at the minimum size. Width and height were each clamped to a minimum of 8 px independently. With 16:9 locked, typing a width of 8 gave a height of 4.5, which was clamped up to 8 β€” an 8 Γ— 8 square while the UI still said 16:9. The fix is a single helper that grows and shrinks both sides together, and fitting inside the image wins over the minimum.
  • A stale result could land on a new file. If you dropped a second GIF while the first was still being cropped, the old job finished later and its output appeared under the new file’s name. Every source change now bumps a generation counter and cancels the running job; a result is only shown if its generation still matches. The same review pattern later found the twin of this bug in file reading β€” a slow read of an earlier file finishing after a newer one β€” which gets the same treatment.

Both are classic UI concurrency and boundary bugs: easy to write, and easy to miss in a test suite that only covers the happy path.

Takeaways

  • Mature C tools travel well. gifsicle compiled to WebAssembly does in the browser what used to need a server, and the result is private by construction: there is nothing to upload.
  • Test on the real headers. The dev server sends no CSP, so the bug that froze production never appeared locally. We now check every tool on a production build served with the real _headers file.
  • Never wait on a worker forever. A watchdog and a clean restart turn β€œstuck” into an error the user can act on.
  • Search instead of guessing. Ordering the options by visual cost β€” lossless, then the gentlest lossy level, then smaller dimensions β€” gives the best result for a byte budget in a handful of runs.
  • Keep the maths pure. Both the size search and the crop geometry are plain functions, which made them easy to test and the bugs easy to fix.

You can try it at gifsmaller.com: pick a goal, drop a GIF, and open the Network tab to see that nothing is uploaded. There is also a GIF cropper and a WebP to GIF converter. Feedback β€” especially GIFs that come out worse than expected β€” is very welcome in the comments.

Credits: gifsicle by Eddie Kohler (GPL-2.0); the WebAssembly build comes from the gifsicle-wasm-browser package.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.