How I hit an exact file size ("under 50 KB") with canvas.toBlob, and the harder "minimum 20 KB" case
Government job portals, university admission forms and visa sites love rules like "photo must be under 50 KB" or "signature between 10 and 20 KB". A JPEG quality slider doesn't help anyone with that. You don't know which
Government job portals, university admission forms and visa sites love rules like "photo must be under 50 KB" or "signature between 10 and 20 KB". A JPEG quality slider doesn't help anyone with that. You don't know which quality value gives 50 KB until you try, and every photo is different.
While building the KB tools for 14FreeTools, I wanted the user to type a number and get a file that fits. Everything had to run client-side, so no photo ever leaves the device. Here's the approach, and the less obvious problem of making a file bigger.
The only knob you have: canvas.toBlob quality
In the browser you draw the image onto a canvas and re-encode it:
function encode(canvas, q) {
return new Promise(r => canvas.toBlob(r, 'image/jpeg', q));
}
File size goes up with q, roughly monotonically. It isn't perfectly smooth, but it's close enough to search.
Binary search on quality
Instead of guessing, search the quality range and keep the best blob that fits:
async function fitUnder(canvas, limit) {
let lo = 0.08, hi = 0.95, best = await encode(canvas, lo);
if (best.size > limit) return null; // can't fit at this pixel size
for (let i = 0; i < 8; i++) {
const mid = (lo + hi) / 2;
const b = await encode(canvas, mid);
if (b.size <= limit) { best = b; lo = mid; }
else hi = mid;
}
return best;
}
Eight rounds narrow the quality to within about 0.003, which is far finer than anyone can see. The result lands just under the limit instead of way below it, so the user keeps as much detail as the rule allows.
When even the lowest quality is too big
A 4000 × 3000 phone photo at quality 0.08 can still be well over 20 KB. Then you have to drop pixels. Size scales roughly with pixel count, so a square-root estimate gets close in one step:
let scale = 1;
while (true) {
const c = draw(img, scale);
const low = await encode(c, 0.08);
if (low.size > limit) {
scale *= Math.max(0.4, Math.sqrt(limit / low.size) * 0.92);
continue;
}
return fitUnder(c, limit);
}
The 0.92 safety factor and the 0.4 floor stop it from overshooting or collapsing the image in a single jump. In practice it settles in one or two rounds.
Two small details that matter:
- Fill the canvas white before drawing. Transparent PNGs otherwise turn black when encoded as JPEG.
- Skip the work if the file already fits. If the input is a JPEG under the limit, return the original untouched. Re-encoding it would only lose quality.
The reverse problem: "minimum 20 KB"
Some forms set a minimum, and people with a tiny 6 KB signature scan get rejected. This one surprised me, because you can't binary-search your way up from a file that's already at maximum quality.
What works, in order:
- Re-encode at quality 0.92, then 1.0. A heavily compressed source often grows a lot just from this.
- If it's still too small, upscale the canvas, again using the square-root estimate (clamped between 1.05× and 2.5× per step).
- If there's also a maximum (for example 20–50 KB) and you overshoot, search the quality down within that window.
- Cap the dimensions (I use 5000 px) so a 2 KB file doesn't turn into a 40-megapixel monster.
On my test signature, a 6 KB file came out at 19.5 KB for a 10–20 KB rule, 22.5 KB for 20–50 KB, 52.5 KB for 50–200 KB and 100.4 KB for 100–300 KB. All of them landed inside the range.
To be honest about it: making a file bigger adds no real detail. It only satisfies a validator. But when the validator stands between someone and a job application deadline, that's the problem worth solving.
Try it
- Fixed limit: Compress image to 50KB, or any number with Reduce image size in KB
- Minimum size: Increase image size in KB
Everything runs in the browser with plain JS and no libraries. I'd like to hear if you've handled the "minimum KB" case differently. Padding the file with junk metadata would also work, but I avoided it on purpose. I wanted the extra bytes to be actual image data.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.