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

How I compress a photo to exactly 50KB in the browser (no uploads)

Government portals, exam registrations and visa forms love strict upload limits: "Photo: JPG, max 50KB. Signature: 10–20KB." Most people solve this by uploading their passport photo to a random website and hoping for the

Government portals, exam registrations and visa forms love strict upload limits: "Photo: JPG, max 50KB. Signature: 10–20KB." Most people solve this by uploading their passport photo to a random website and hoping for the best.

I wanted a tool where you type a target size and get the best-looking JPG that fits under it, without the photo ever leaving the device. That became FreeCompressJPG. Here's how the "compress to exact size" part works, in about 50 lines of plain browser JavaScript.

The problem: JPEG quality isn't linear

canvas.toBlob(cb, 'image/jpeg', quality) lets you pick a quality between 0 and 1, but there's no formula that maps "50KB" to a quality value. It depends entirely on the image: a white-background signature at quality 0.9 might be 15KB, while a detailed face photo at 0.5 might still be 120KB.

What we do know is that, for a given image, file size grows with quality. So we can binary-search it.

Step 1: decode and draw

const bmp = await createImageBitmap(file); // JPG, PNG, WebP, BMP, AVIF…

function draw(bmp, scale) {
  const c = document.createElement('canvas');
  c.width = Math.max(1, Math.round(bmp.width * scale));
  c.height = Math.max(1, Math.round(bmp.height * scale));
  const g = c.getContext('2d');
  g.fillStyle = '#fff';             // JPG has no transparency
  g.fillRect(0, 0, c.width, c.height);
  g.imageSmoothingQuality = 'high';
  g.drawImage(bmp, 0, 0, c.width, c.height);
  return c;
}

const encode = (c, q) =>
  new Promise((res) => c.toBlob(res, 'image/jpeg', q));

The white fill matters: a transparent PNG drawn straight onto a JPEG canvas turns its transparent areas black.

Step 2: binary-search the quality

const MIN_Q = 0.4; // below this, JPEG artifacts get ugly

async function bestQuality(canvas, target) {
  const low = await encode(canvas, MIN_Q);
  if (low.size > target) return null;          // won't fit at this resolution

  const top = await encode(canvas, 0.95);
  if (top.size <= target) return top;          // already small enough

  let lo = MIN_Q, hi = 0.95, best = low;
  for (let i = 0; i < 7; i++) {                // ~0.01 precision
    const mid = (lo + hi) / 2;
    const blob = await encode(canvas, mid);
    if (blob.size <= target) { best = blob; lo = mid; } else hi = mid;
  }
  return best;
}

Seven iterations narrow a 0.55-wide range down to about 0.004, which is far below anything you can see. Each toBlob call takes a few milliseconds for a typical photo, so the whole search feels instant.

Step 3: if quality alone isn't enough, shrink the pixels

A 12-megapixel phone photo will never fit in 20KB, whatever the quality. Rather than dropping quality to an awful 0.1, I reduce the dimensions and search again:

let scale = 1;
for (let attempt = 0; attempt < 12; attempt++) {
  const c = draw(bmp, scale);
  const blob = await bestQuality(c, target);
  if (blob) return blob;

  const probe = await encode(c, MIN_Q);
  // JPEG bytes scale roughly with pixel count, so shrink the *area*
  // by the overshoot ratio (sqrt for each side), with a 5% margin.
  scale *= Math.sqrt(target / probe.size) * 0.95;
}

Because file size is roughly proportional to the number of pixels, sqrt(target / actual) gets close on the first try. Usually one resize is enough.

Step 4: "50KB" means 50,000 bytes

This one bit me. Some upload forms count 1KB as 1,000 bytes, others as 1,024. If you aim for 51,200 bytes, the first kind rejects you. So the target is always kb * 1000. That's slightly stricter than needed, but it passes both checks.

Why do it in the browser at all?

  • Privacy. These are passport photos, signatures and ID scans. They shouldn't sit on someone else's server, even for "1 hour before automatic deletion".
  • Speed. There's no upload or download round trip. A batch of 20 photos finishes before a server-side tool would have uploaded the first one.
  • Cost. There's no image-processing backend to pay for, so the tool can stay free without daily limits.

You don't have to take my word for "nothing is uploaded". Open DevTools → Network, drop in a photo and watch: you'll see no request carrying the image. Once the page has loaded you can even switch Wi-Fi off and it keeps working. (In the interest of full transparency: the page does send an anonymous "a file was compressed" counter so I know which tools get used. It contains no file data, no filename and no identifier.)

Try it

It's free, needs no sign-up and adds no watermark. It's available in 17 languages, because strict upload limits aren't an English-only problem.

I'd love feedback, especially on edge cases: images that come out blurrier than you'd expect, or forms that still reject the output.

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