DEV Community

Cover image for Hitting an exact KB target with browser canvas compression in 10 binary search steps
Ken
Ken

Posted on AI-assisted

Hitting an exact KB target with browser canvas compression in 10 binary search steps

Half the time when someone opens an image compressor, they do not actually care whether quality is set to 72% or 78%. They have a form yelling at them that their upload must be under 200 KB or 500 KB.

Dragging a quality slider back and forth and guessing the resulting file size is annoying. When I built the live image compressor in Imagier, I added a target KB input alongside the usual quality slider. Everything runs locally in the browser using canvas.toBlob, and getting close to the exact byte limit takes about 15 lines of code.

Binary search over encoder quality

For lossy formats like image/webp and image/jpeg, output file size grows monotonically with the quality argument (0.01 to 1.0) in canvas.toBlob(cb, type, quality). That means you do not have to step through qualities linearly. Binary search finds the highest quality that still fits under the byte limit in just 10 iterations (narrowing the quality range to roughly 0.001 precision):

export async function encodeToTarget<T extends { size: number }>(
  targetBytes: number,
  encode: (quality: number) => Promise<T>
) {
  if (!Number.isFinite(targetBytes) || targetBytes <= 0) {
    throw new Error('Choose a positive target file size.');
  }

  // Fast path: already fits at max quality.
  const highQuality = await encode(1);
  if (highQuality.size <= targetBytes) return highQuality;

  // Guard rail: even the lowest quality cannot hit the target.
  let best = await encode(0.01);
  if (best.size > targetBytes) return best;

  let low = 0.01;
  let high = 1;
  for (let index = 0; index < 10; index++) {
    const quality = (low + high) / 2;
    const candidate = await encode(quality);
    if (candidate.size <= targetBytes) {
      best = candidate;
      low = quality;
    } else {
      high = quality;
    }
  }

  return best;
}
Enter fullscreen mode Exit fullscreen mode

Checking both endpoints (1.0 and 0.01) before starting the loop pays off immediately:

  1. If the image is already small enough at full quality, you finish in a single encode instead of doing 10 extra passes.
  2. If the user asks for 20 KB on a 5000x3000 photo, you fail fast after two encodes and tell them to scale the dimensions down first rather than burning CPU trying to squeeze blood from a stone.

Three small gotchas with canvas.toBlob

If you wire this up yourself, a few browser quirks are worth handling right away:

  • Format fallback: If a browser does not support encoding a requested MIME type (historically an issue with WebP on older Safari builds), canvas.toBlob silently falls back to image/png. Always verify blob.type === requestedType so you do not tell the user they got a WebP when it is actually a huge PNG.
  • Transparent pixels in JPEG: Canvas backgrounds default to transparent black. Before encoding image/jpeg, fill the canvas with a solid color (usually #ffffff) or transparent areas will turn pitch black.
  • Releasing canvas memory: After encoding, shrink temporary offscreen canvases down (canvas.width = 1; canvas.height = 1) and call bitmap.close() on any ImageBitmap. On Safari and mobile browsers, forgetting this can hit canvas memory limits fast during batch compression.

Live preview without flashing

One nice UX touch on top of this: whenever the user drags the quality slider or changes the target KB, debounce the re-encode by ~220ms and keep displaying the previous compressed blob in the split-view comparison until the new blob resolves. That way the before/after slider never flickers to an empty state while tuning compression.

You can test the target KB mode and the live split-view comparison at imagier.app/tools/image-compressor (there is a 1-click sample image if you do not have one handy). And if an image still cannot hit a tiny byte target at full resolution, pairing it with imagier.app/tools/image-resizer usually drops the file size by another 60 to 80%.

Top comments (0)