DEV Community

Nawal Shrestha
Nawal Shrestha

Posted on Originally published at getsnapshrink.com

Stop Guessing the Quality Slider — Binary-Searching JPEG Quality for Exact File Sizes

Here's a UX problem every image tool punts on: the user doesn't want "quality 80". They want "under 100KB" — because a form said so. The quality slider is the tool's internal machinery exposed as UI. Users shouldn't have to learn your encoder's quality curve.

In SnapShrink I built Target KB mode: type 20, get a file at or under 20KB. Here's the approach.

The algorithm

It's a binary search over the quality parameter:

  1. Set bounds: quality 1–100 (or your encoder's range).
  2. Encode at mid quality, measure the output bytes.
  3. If over target, search the lower half; if under, search the upper half — keeping the best valid result.
  4. ~7 iterations converges. Each iteration is a fast in-memory encode; no network involved.

The key detail: quality is searched first, dimensions last. Only if quality=1 still overshoots do you downscale slightly and re-run the search. Most photos hit common caps (20/50/100KB) with dimensions untouched, which is what users expect — they asked for a size, not a resize.

Why this matters more than it sounds

  • Government and exam portals (India's UPSC forms: 20–300KB caps) reject oversized uploads with zero guidance. "Type the number" beats a slider every time.
  • It composes with batch: set the target once, every file in the batch gets its own binary search, download as ZIP.
  • It works client-side. The encodes are cheap enough to run in a Web Worker without blocking the page.

The honest edge cases

  • Tiny targets on huge photos will visibly degrade — that's physics, not a bug. Showing the achieved size when the target is unreachable beats silently overshooting.
  • PNGs with sharp text compress differently than photos; the search handles both because it measures actual bytes, not estimates.

If you maintain an image tool, consider exposing the target instead of (or alongside) the slider. Users think in file sizes. Meet them there.

Live at getsnapshrink.com/compress-image-to-exact-kb/ — first 10 images per session free, everything runs in the browser. The same engine also powers HEIC→JPG and AVIF→JPG conversion — new input formats turned out to be just a decode step.

Top comments (0)