Compress an image to an exact KB limit in the browser (binary search + canvas.toBlob)
Government and exam portals in India (SSC, RRB, UPSC, bank exams, NSDL PAN) are strict about upload sizes: "Photo: JPG, 20 KB to 50 KB". A file of 50.3 KB gets rejected. Most online compressors only give you a "quality %
Government and exam portals in India (SSC, RRB, UPSC, bank exams, NSDL PAN) are strict about upload sizes: "Photo: JPG, 20 KB to 50 KB". A file of 50.3 KB gets rejected. Most online compressors only give you a "quality %" slider, so users guess, upload, fail, and guess again.
I wanted a function where you say "make this fit under 20 KB" and it returns the best-looking JPG that fits, without sending the photo to any server. Here is how it works, in about 90 lines of plain JavaScript and no libraries.
The idea in one line
JPEG file size goes down (almost always) as quality goes down, so you can binary-search the quality until the file is just under the limit.
Step 1: Encode a canvas at a given quality
canvas.toBlob() is callback-based, so wrap it in a Promise:
const encode = (canvas, type, q) =>
new Promise(res => canvas.toBlob(b => res(b), type, q));
When drawing, fill the canvas white first. JPG has no transparency, and a transparent PNG would otherwise turn black:
function drawScaled(img, w, h) {
const c = document.createElement('canvas');
c.width = w; c.height = h;
const x = c.getContext('2d');
x.fillStyle = '#fff';
x.fillRect(0, 0, w, h);
x.imageSmoothingQuality = 'high';
x.drawImage(img, 0, 0, w, h);
return c;
}
Step 2: Binary-search the quality
Try 0.95 first. If that already fits, we are done. Otherwise search between 0.05 and 0.95, keeping the best result that fits:
async function bestQuality(canvas, type, maxBytes) {
let b = await encode(canvas, type, 0.95);
if (b.size <= maxBytes) return { blob: b, quality: 0.95 };
let lo = 0.05, hi = 0.95, got = null;
for (let k = 0; k < 8; k++) {
const m = (lo + hi) / 2;
b = await encode(canvas, type, m);
if (b.size <= maxBytes) { got = { blob: b, quality: m }; lo = m; }
else hi = m;
// stop early once we're within 2% of the limit
if (got && maxBytes - got.blob.size < maxBytes * 0.02) break;
}
return got; // null = doesn't fit even at the lowest quality
}
Eight iterations narrow the quality down to well under 1%, which is more precision than the eye can see. Each encode of a passport-size photo takes a few milliseconds, so the whole search feels instant.
Step 3: Start from a sensible pixel size
A 12 MP phone photo will never fit in 20 KB at a usable quality. Searching quality alone would just return a blocky mess. So before searching, scale the image to a pixel budget that matches the target. For typical photos, roughly 0.11 bytes per pixel at decent JPEG quality is a good starting point:
const capPx = Math.max(160 * 160, maxBytes / 0.11);
let s = Math.min(1, Math.sqrt(capPx / (img.width * img.height)));
let W = Math.round(img.width * s), H = Math.round(img.height * s);
If even the lowest quality is still too big (noisy photos, busy backgrounds), shrink the pixels by 15% and search again:
for (let tries = 0; tries < 14; tries++) {
const r = await bestQuality(drawScaled(img, W, H), type, maxBytes);
if (r) return { blob: r.blob, width: W, height: H, quality: r.quality };
W = Math.round(W * 0.85); H = Math.round(H * 0.85);
}
throw new Error('Could not fit the image under ' + maxKB + ' KB');
Step 4: Keep a safety margin
Portals don't agree on what "KB" means. Some use 1,000 bytes, some 1,024. Some round, some don't. So I target 1 KB below the limit and treat 1 KB as 1,000 bytes. A "20 KB" target never produces anything above 19,000 bytes, which passes every checker I've tested.
const maxBytes = Math.round((maxKB > 2 ? maxKB - 1 : maxKB * 0.95) * 1000);
Step 5: The minimum-size problem
Here's the part that surprised me: many forms also have a minimum ("10 KB to 20 KB"). A small signature on white paper can compress to 6 KB, which gets rejected for being too small.
You don't want to add noise or re-encode at a worse ratio. JPEG has a comment segment (0xFFFE) that decoders ignore. Inserting padding there raises the file size without touching a single pixel:
// seg = [0xFF, 0xFE, lenHi, lenLo, ...spaces]
const seg = new Uint8Array(len + 2);
seg[0] = 0xFF; seg[1] = 0xFE; seg[2] = len >> 8; seg[3] = len & 255;
seg.fill(32, 4);
Insert it after the JFIF APP0 header (not before it, or some strict validators complain), and split it into chunks if you need more than 65,533 bytes.
Bonus: setting DPI
Some forms (PAN card applications, for example) check DPI too. In a JFIF JPEG, density lives at fixed bytes 13 to 17 of the file, so it's a direct byte write, with no re-encoding:
u[13] = 1; // units: dots per inch
u[14] = dpi >> 8; u[15] = dpi & 255; // X density
u[16] = dpi >> 8; u[17] = dpi & 255; // Y density
Usage
const { blob, width, height, quality } = await compressToKB(file, 20);
// range + DPI:
await compressToKB(file, 50, { minKB: 20, dpi: 200 });
Why do it client-side?
These are ID photos and signatures. Nobody should have to upload those to a random server just to shrink a file. Doing everything with createImageBitmap + canvas means the image never leaves the device, and there's no backend to pay for.
Code
The full script (MIT licensed) is on GitHub: girishkapale/kb-compressor.
Disclosure: I built this for my own site, ToolsKB, where it runs with exam presets (SSC, RRB, UPSC, PAN), signature cleanup and JPG-to-PDF. But the function above works on its own, so feel free to drop it into your own project.
What would you add? I'm thinking about WebP output and a smarter starting bytes-per-pixel estimate based on image entropy.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.