Hitting an exact KB range in the browser: how we compress exam photos and PDFs without a server
Indian exam and job portals are strict about file sizes in a way most compressors aren't built for. SBI wants a photo of 20–50 KB. UPSC wants a signature image of 20–100 KB at 350–500 px. SSC wants a signature of 10–20 K
Indian exam and job portals are strict about file sizes in a way most compressors aren't built for. SBI wants a photo of 20–50 KB. UPSC wants a signature image of 20–100 KB at 350–500 px. SSC wants a signature of 10–20 KB. Upload 51 KB and you're rejected. Upload 19 KB and you're rejected too.
We built ToolFreely to hit those windows, entirely in the browser, because the files are faces, signatures and marksheets that nobody should have to upload to a stranger's server. (Disclosure: I built it.) Here's how it works.
The stack, briefly
The site is static Astro, and each tool page hydrates a React island on load. Everything heavy is loaded only when needed: pdf.js and pdf-lib download when you open a PDF, and the HEIC decoder when you pick a HEIC file. A visitor who only resizes a JPEG never downloads about a megabyte of PDF code.
Problem 1: "KB" has two meanings
Some portals count 1 KB as 1,000 bytes, others as 1,024. We can't know which, so we target the intersection:
// simplified from the production bundle
const maxBytes = Math.floor(maxKb * 1000) - 48; // strict ceiling, small safety margin
const minBytes = Math.ceil(minKb * 1024); // strict floor
A file between those two numbers passes under either convention. The UI also prints the result three ways, e.g. 32,827 bytes · 32.8 KB (1,000) · 32.1 KB (1,024), so users can check it against whatever the portal says.
Problem 2: Hitting a window, not just a ceiling
Most "compress to X KB" tools lower quality until the file is under X. With a 20–50 KB window, that often lands on 12 KB or misses entirely. We do a binary search on JPEG quality, aiming at the middle of the window:
let lo = 0.08, hi = 0.92; // quality bounds
for (let step = 0; step < 8 && hi - lo > 0.03; step++) {
const q = (lo + hi) / 2;
const bytes = await encode(q, scale); // canvas.toBlob('image/jpeg', q)
if (bytes > win.maxBytes) hi = q;
else if (bytes < win.minBytes) lo = q;
else if (Math.abs(bytes - mid) / win.maxBytes < 0.04) break; // close enough
else (bytes > mid) ? hi = q : lo = q;
}
If the file is still too big at the lowest quality, we shrink the dimensions instead of destroying the image. The new scale is estimated from how far over we are, scale * Math.sqrt(maxBytes / bytes) * 0.92, with a floor of 15% of the original size. Then the search runs again. There's a hard cap of 12 encodes in total, so a phone never gets stuck. The result reports whether it landed inside, under or over, and the UI tells the user which.
Presets where the notice demands exact pixels, or centimetres at a stated DPI, turn off down-scaling, so only quality moves. A "preferred" size like SBI's 200 × 230 px may still shrink if that's the only way to fit.
Problem 3: Minimums are as real as maximums
Plenty of people have the opposite problem: "your file must be at least 10 KB". A tiny, clean signature can compress to 6 KB. Re-encoding at higher quality doesn't always help.
Our "increase size" mode pads the JPEG instead. It inserts a COM (comment) segment (0xFF 0xFE) just before the end-of-image marker. The pixels don't change, decoders ignore the comment, and the byte count goes up to the minimum.
Problem 4: Photos from phones lie about their orientation
Phone photos often store the rotation in EXIF rather than in the pixels. We decode with createImageBitmap(blob, { imageOrientation: 'none' }), read the EXIF orientation ourselves, and apply the matching canvas transform (all 8 cases). That way every browser gives the same result, and a cropped passport photo never comes out sideways.
Some presets give sizes in centimetres plus a DPI. For those we also write the density into the JPEG's JFIF header, or the pHYs chunk for PNG with its CRC, so "3.5 × 4.5 cm at 200 DPI" means the same thing in an image viewer.
Problem 5: PDFs are pictures more often than you think
Most "PDF too big" files are scans: each page is a photo. Our PDF compressor is deliberately simple:
- Render each page with pdf.js to a canvas.
- Optionally convert to grayscale (BT.601 luma:
0.299R + 0.587G + 0.114B). - Encode each page as JPEG and add up the bytes.
- Try a fixed ladder of render scale × quality,
[1.5, 1.15, 0.85] × [0.72, 0.55, 0.42], and stop at the first combination that fits. - Rebuild the document with pdf-lib by embedding each page JPEG.
The important design decision is what happens when nothing fits. The tool throws an error instead of writing a smaller, unreadable file: "Going further would make the text hard to read, so no file was saved." A blurry marksheet that gets rejected after the deadline is worse than an honest error now.
The trade-off is stated in the UI too: pages become images, so the text is no longer selectable. There are also hard limits of 30 MB and 20 pages, because every page is rendered to a canvas on the user's own device. Twenty pages is the cap that keeps a mid-range phone from running out of memory while it renders them.
Problem 6: Specs are data, not copy
The exam limits live in a JSON array. Each preset has min_kb, max_kb, pixel or centimetre dimensions, DPI, notes, and a source_url pointing to the official notice PDF. The UI shows a "last checked" date. When a notice says "about 6.0 cm × 2.0 cm" but gives no DPI, the tool stops and says: "This notice gives centimetres but no DPI. Choose 200 or 300 — that choice is not written in the notice." When a new notice comes out, the preset is updated to match it.
How we check "no upload"
A Content-Security-Policy isn't proof: ours still allows connect-src https: for analytics and ads. So we test it the boring way. We load the page in a headless browser, run the tool, and log every request. After a file is picked, the only outgoing call is a small first-party analytics beacon to /a/e. It carries the event name, the page path and the screen width; pageviews also include the referrer and UTM source. The file never leaves the tab. (The pages do show Google AdSense ads, which is how the site stays free.)
What we'd tell anyone building this
- Design for windows, not ceilings. A minimum KB is a common failure.
- Pick the strictest reading of ambiguous units, and show the user the raw bytes.
- Lazy-load the heavy stuff. Most visitors need only one tool.
- Fail loudly rather than hand back a file that will be rejected.
- Verify privacy claims with a network log, not with marketing copy.
If you want to poke at it, the 20–50 KB photo compressor and the PDF-to-500 KB compressor are the two pages described here. Open DevTools → Network while you use them. Weird PDFs and edge cases are welcome in the comments.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.