Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Compressing images in the browser: the memory trap nobody mentions

Converting an image to WebP in the browser is twelve lines of code. Doing it without crashing a phone is a different problem, and the crash is not where you expect it. The part that works const bitmap = aw

Converting an image to WebP in the browser is twelve lines of code. Doing it without crashing a phone is a different problem, and the crash is not where you expect it.

The part that works

const bitmap = await createImageBitmap(file);
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext('2d').drawImage(bitmap, 0, 0);

const blob = await new Promise((resolve) =>
  canvas.toBlob(resolve, 'image/webp', 0.8)
);

That is the whole conversion. blob.size is your new file, and 0.8 is usually indistinguishable from the original at normal viewing size.

Now the problems, in the order they bite.

Problem 1 — the memory bill arrives before the encode

A 12 MP photo is roughly 48 MB when decoded to RGBA, because every pixel costs four bytes whether the JPEG used one or not. Add the source bitmap still in memory plus the canvas backing store, and a single 12 MP photo can hold 100–150 MB while the tab is busy.

On a laptop that is invisible. On a mid-range Android phone with a browser capped around 300 MB per tab, it is the difference between "compressed" and "Aw, snap".

The fix is to not decode at full size when you do not need full size:

// Downscale in steps instead of one jump
async function downscale(file, targetWidth) {
  let bitmap = await createImageBitmap(file);
  let current = bitmap.width;

  while (current / 2 > targetWidth) {
    current = Math.round(current / 2);
    const c = new OffscreenCanvas(current, Math.round(bitmap.height * current / bitmap.width));
    const ctx = c.getContext('2d');
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(bitmap, 0, 0, c.width, c.height);
    bitmap = await createImageBitmap(c);
  }
  return bitmap;
}

One jump from 4000px to 800px is a single huge resample; three halvings of a smaller bitmap each time is both faster and sharper on most engines. OffscreenCanvas also keeps the work off the main thread when you use it inside a worker.

Problem 2 — "target 100 KB" has no direct answer

There is no setting that means "100 KB". Quality is a proxy for size, and the mapping between them depends on the image content. A flat gradient compresses beautifully at 0.6; a photograph of foliage does not.

So search for it:

async function toTargetSize(bitmap, targetKB, type = 'image/webp') {
  const canvas = document.createElement('canvas');
  canvas.width = bitmap.width;
  canvas.height = bitmap.height;
  canvas.getContext('2d').drawImage(bitmap, 0, 0);

  let low = 0.05, high = 0.95, best = null;

  for (let i = 0; i < 8; i++) {
    const q = (low + high) / 2;
    const blob = await new Promise((r) => canvas.toBlob(r, type, q));
    if (!blob) break;

    if (blob.size / 1024 <= targetKB) {
      best = blob;      // fits, try for better quality
      low = q;
    } else {
      high = q;         // too big, go lower
    }
  }
  return best;          // null means the target is impossible
}

Eight passes, roughly 100–200 ms, and you get the highest quality that still fits. Two details matter: bail out after a fixed number of passes, and return null honestly when no quality fits, instead of looping until the tab dies.

Problem 3 — resizing beats compressing

Users ask for a size, but what they usually need is a smaller image. If the file is 4000px wide and will be displayed at 800px, the right move is to resize, not to crush the quality.

Approach Result on a 3 MB photo Visual quality
4000px at quality 0.35 100 KB visible blocking
1600px at quality 0.72 ~95 KB clean
1200px at quality 0.8 ~90 KB clean

At the same file size, the resized version looks better every time. That is why a good compressor asks for the display width, not just the quality slider.

Problem 4 — format choice is per image, not per site

  • Photographs → WebP (or AVIF), quality 0.72–0.8
  • Screenshots and text → PNG or lossless WebP; JPEG turns text into mush
  • Flat graphics, logos → SVG if possible, PNG otherwise
  • Transparency → WebP or PNG; JPEG has none

Safari's encoder is also slower than Chrome's and occasionally returns a larger file than the JPEG source. Always compare blob.size with file.size and keep whichever is smaller.

The rule I ended up with

  1. Decode at the size you need, not the size the camera produced
  2. Search for quality, cap the passes, and fail honestly
  3. Prefer resizing over compression
  4. Compare output size with input size before offering the download

None of this needs a server. That matters for more than speed: a CV, a passport scan, or a client screenshot should not have to travel to someone else's disk to be compressed. The browser can do the whole job locally, and modern APIs make it practical.

I build browser-only tools — the image side is WebPTools, the PDF side is PDFClicks, and the smaller utilities are on ILoveDevs. Nothing uploads; everything runs in the tab.

📰 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.