DEV Community

Hasibul Mawla
Hasibul Mawla

Posted on

How to Compress an Image to an Exact Size in KB, in the Browser

Most image compressors answer the wrong question. They make a file smaller. But the user staring at an upload form does not need "smaller". The form says 50 KB or less, and 51 KB fails exactly the same way 5 MB fails.

I ran into this building the image compressor on BrightFreeTools (disclosure: it is my site). People were not trying to optimize images for a website. They were trying to get a photo under the limit of a job application, an exam form, a government portal. So the tool had to hit a target, not just shrink. Here is how it works, and the two traps that took the longest to get right.

The two levers, and why order matters

A JPEG's size is controlled by two things: the quality setting and the pixel dimensions. The naive approach is to keep lowering quality until the file fits. That works, but at quality 0.3 everything looks like it was photographed through frosted glass.

The better order is:

  1. Hold quality in the range that still looks clean (around 0.7 to 0.8 for photos).
  2. Search the quality setting first, at the current dimensions.
  3. If even the lowest acceptable quality is too big, scale the dimensions down and search again.

Shrinking a 4000×3000 photo to 800×600 loses far less visible quality than crushing its JPEG quality, because forms and phones display it small anyway. You are throwing away pixels nobody would have seen, instead of mangling the pixels they do see.

Searching instead of guessing

There is no formula that maps quality to bytes — it depends entirely on the image content. A photo of a plain wall compresses to almost nothing; a photo of a crowd at the same quality can be ten times larger. So you cannot compute the right setting. You have to search for it.

JPEG size is monotonic in quality: higher quality never produces a smaller file. That makes it a textbook binary search. Encode, measure, adjust:

async function encodeAtQuality(canvas, quality, type = "image/jpeg") {
  return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
}

async function fitByQuality(img, targetBytes) {
  const canvas = document.createElement("canvas");
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  canvas.getContext("2d").drawImage(img, 0, 0);

  let lo = 0.3, hi = 0.95, best = null;
  while (hi - lo > 0.02) {
    const mid = (lo + hi) / 2;
    const blob = await encodeAtQuality(canvas, mid);
    if (blob.size <= targetBytes) {
      best = blob;      // fits — try to do better
      lo = mid;
    } else {
      hi = mid;         // too big — lower the quality
    }
  }
  return best; // null means: even 0.3 was too big at this size
}
Enter fullscreen mode Exit fullscreen mode

If that returns null, draw the image onto a smaller canvas (say 85% of the dimensions) and run the same search again. Each round keeps the best-looking version that fits. A handful of encodes per round is cheap — this all runs in a few hundred milliseconds on a phone, and the file never leaves the device.

Trap 1: a kilobyte is not a kilobyte

This one cost real debugging time. Windows and many websites count 1 KB as 1,024 bytes. Phones, Macs and other websites count 1 KB as 1,000 bytes. So the same file is "50 KB" on one screen and "48.8 KB" on another, and a form can reject a file that your compressor swore was exactly at the limit.

The fix is to budget in bytes, using the strict count: a 50 KB target means at most 50,000 bytes. Then the result passes no matter which way the form counts. (It also means your displayed size should round up, so a file that is over a limit never looks under it.)

Trap 2: forms that reject files for being too small

Some forms specify a range: "between 20 KB and 50 KB". Too small is also a failure. Hitting a floor is the mirror problem: raise the quality first, and if the file is still under the minimum at maximum quality, scale the dimensions up until it reaches the floor. Upscaling adds no detail, and it feels wrong, but it satisfies the rule — and it is what the form is actually checking.

What the numbers look like in practice

These are real measurements from the live tool, November 2026. Both test photos are 12 MP iPhone shots (4032×3024):

Target Landscape photo Portrait photo (detailed)
20 KB 373×279 245×327
50 KB 655×491 387×516
100 KB 985×738 548×730
200 KB 1491×1119 860×1146

JPEG quality stayed between 70% and 80% in all of them — the dimensions did the work. Your numbers will differ: fine detail (leaves, crowds, printed text) needs more bytes, plain backgrounds need fewer.

Two honest limitations

PNG does not play along. PNG is lossless, so there is no quality lever — the only way under a small target is drastically smaller dimensions. The tool warns and suggests JPEG when that happens. WebP compresses better than JPEG at the same quality, but too many official forms still refuse it.

Binary search means several encodes. For a batch of 20 images that is real work on a low-end phone. It is still faster than uploading 5 MB per photo on a slow connection — which is the alternative, and the reason the whole thing runs client-side in the first place: no upload, no server holding anyone's ID photos, nothing to leak.

If you want to try the finished version, it is the image compressor on BrightFreeTools — free, no sign-up, everything happens in your browser. And if you hit an edge case it handles badly, I genuinely want to hear about it in the comments.

Top comments (0)