DEV Community

Cover image for How to Compress an Image to an Exact KB Size in the Browser (Free, No Upload)
Abhigyan Saikia
Abhigyan Saikia

Posted on

How to Compress an Image to an Exact KB Size in the Browser (Free, No Upload)

Upload forms don't ask for "80% quality". They ask for "photo under 50KB". And every mainstream compressor hands you a quality slider and wishes you luck — compress, check size, adjust, repeat.
There are three ways to hit an exact KB target. Here's all of them.

Option 1: ImageMagick (one line)
If you're on a machine with ImageMagick installed:
magick input.jpg -define jpeg:extent=50KB output.jpg
The jpeg:extent define binary-searches the quality for you. Change 50KB to whatever the form wants. Fast, scriptable, exact.

Option 2: Do it in the browser with Canvas

The same binary-search idea works client-side. Sketch of the approach:
async function compressToKB(file, targetKB) {
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);

let low = 0.05, high = 0.95, best = null;
for (let i = 0; i < 8; i++) { // 8 rounds is plenty
const q = (low + high) / 2;
const blob = await new Promise(r => canvas.toBlob(r, 'image/jpeg', q));
if (blob.size <= targetKB * 1024) { best = blob; low = q; }
else { high = q; }
}
// If quality alone can't reach it, shrink dimensions and repeat.
return best;
}
Eight iterations converge fast. If the lowest quality still overshoots, halve the dimensions and run again — pixel count dominates file size.

Option 3: Use a tool that does this already (disclosure: I built it)

I got tired of doing the slider dance for exam forms, so I built ToolKB — you type the exact KB target (20KB, 50KB, 100KB, anything up to 10MB) and it runs the binary search above entirely in your browser.
Why in-browser matters: these are identity documents — passport photos, signatures. Nothing uploads anywhere; you can watch the Network tab and see zero outgoing transfers. No signup, no watermark, no daily limit.
Handy presets if you're filling Indian exam forms:
Signature to 20KB — SSC/IBPS signature spec (10–20KB)
Photo to 50KB — SSC GD / IBPS photo range
Photo to 200KB — UPSC photo spec

The rule of thumb

File size ≈ pixels × quality. If your 12MP phone photo won't squeeze into 50KB without turning to mush, don't just crush the quality — halve the dimensions first (that quarters the pixels), then compress. Sharper result, same file size.

Top comments (0)