Job portals, university admissions and government forms love strict upload limits: "Photo must be under 50 KB", "Signature must be under 20 KB". Most online compressors give you a quality slider and leave you to guess. I wanted a tool where you type 50 KB and get the best-looking JPG that fits, without uploading the photo to a server.
It turns out you can do this in about 60 lines of plain JavaScript. Here's the approach I used.
1. Draw the image onto a canvas
The browser already has a JPEG encoder: canvas.toBlob(). We just need the image on a canvas first.
function draw(img, w, h) {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
const ctx = c.getContext('2d');
ctx.fillStyle = '#fff'; // JPEG has no transparency, so fill PNG gaps with white
ctx.fillRect(0, 0, w, h);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, w, h);
return c;
}
const toBlob = (canvas, q) =>
new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', q));
The white fill matters: without it, transparent PNG areas turn black in the JPG.
2. Binary-search the JPEG quality
File size grows with quality, so finding the highest quality that still fits is a classic binary search. Seven rounds gets you within about 1% of the best value.
async function bestQuality(canvas, limitBytes) {
let lo = 0.05, hi = 0.95, best = null;
const top = await toBlob(canvas, hi);
if (top.size <= limitBytes) return { blob: top, q: hi }; // already fits
for (let i = 0; i < 7; i++) {
const mid = (lo + hi) / 2;
const blob = await toBlob(canvas, mid);
if (blob.size <= limitBytes) { best = { blob, q: mid }; lo = mid; }
else hi = mid;
}
return best; // null if even low quality is too big at this size
}
3. Prefer a smaller sharp image over a big blurry one
This is the part most tools skip. If a 4000 × 3000 phone photo has to fit in 20 KB, quality 5% looks terrible. Shrinking the image a bit and keeping quality at 70% looks far better, and forms rarely need 12 megapixels anyway.
So the search runs in tiers. First it tries to keep quality at 70% or more, shrinking the image by 15% at a time. Only if that fails does it accept 50%, then 30%, and finally anything.
async function compressToSize(img, targetKb) {
const limit = targetKb * 1024;
const startW = img.naturalWidth, startH = img.naturalHeight;
for (const minQ of [0.7, 0.5, 0.3, 0.05]) {
let w = startW, h = startH;
for (let step = 0; step < 30; step++) {
const r = await bestQuality(draw(img, w, h), limit);
if (r && r.q >= minQ) return { ...r, w, h };
if (Math.max(w, h) <= (minQ > 0.05 ? 400 : 16)) break; // don't go too small at this tier
w = Math.max(16, Math.round(w * 0.85));
h = Math.max(16, Math.round(h * 0.85));
}
}
return null; // genuinely impossible, so ask for a bigger target
}
The 400 px floor stops the good-quality tiers from turning a passport photo into a thumbnail. Only the last tier is allowed to go really small.
4. Hook it up
input.addEventListener('change', async () => {
const file = input.files[0];
const img = new Image();
img.src = URL.createObjectURL(file);
await img.decode();
const result = await compressToSize(img, 50);
if (!result) return alert('Could not reach 50 KB. Try a larger target.');
link.href = URL.createObjectURL(result.blob);
link.download = file.name.replace(/\.[^.]+$/, '') + '-50kb.jpg';
console.log(`${result.w}×${result.h} at ${Math.round(result.q * 100)}% → ${(result.blob.size / 1024).toFixed(1)} KB`);
});
Everything stays on the user's device, so there's no server cost and no privacy worry about ID photos.
Things I learned
-
toBlobis async and fairly fast. A full search is usually 10–40 encodes, which takes well under a second for normal photos. - Cancel stale runs. If the user changes the target while a search is running, keep a job counter and drop results from older runs.
- HEIC won't decode in most browsers outside Safari, so tell iPhone users to export as JPG first.
- Big targets don't need tiers. For 200 KB and up, the first pass almost always fits at full size.
Try it
If you want to see it working, I built this into a free tool: Compress Image to KB. Pick 20, 50, 100 or 200 KB, or type any size. It's part of DailyNexaTools, a set of free browser-based tools I'm building (PDF, image, developer tools and calculators), with no sign-up and no uploads.
Questions or improvements welcome in the comments. I'd especially like to hear if anyone has tried WebP or AVIF output for size targets.
Top comments (0)