Dev.to · 2 min read

Hitting an exact file size when compressing images in the browser

Hitting an exact file size when compressing images in the browser

India's chartered accountancy board caps the photo you upload with your exam form at 50 KB. South Africa's tax service wants supporting documents under 2 MB. A French rental platform stops at 10 MB per file. Canada's immigration portal has its own number. None of these portals will compress your file for you. They reject it and let you work it out. A photo from a modern phone is 3 to 5 MB. Getting it to 50 KB means dividing its weight by about eighty, and the obvious approach — pick a JPEG quality, encode, hope — doesn't survive contact with real files. Here's what actually works, and why the naive version fails. Quality is not a dial you can read The temptation is to map file size onto quality: 50 KB is small, so use quality 0.3. That fails because JPEG quality isn't a size setting. It's a quantization parameter, and how many bytes it produces depends entirely on the image. A photo of a blank wall at quality 0.9 can be smaller than a photo of a forest at quality 0.4. Noise, texture and detail decide the output size, not the number you passed in. So you can't compute the quality you need. You have to find it. Binary search Encoding to a canvas is cheap enough to do repeatedly, which makes this a search problem. The quality range you care about is roughly 0.25 to 0.95 — below 0.25 the artifacts are bad enough that the result is useless anyway. let lo = 0.25, hi = 0.95, found = null; for (let i = 0; i < 7; i++) { const q = (lo + hi) / 2; const blob = await encodeImage(bmp, scale, q, type); if (blob.size

This is a summary aggregated from Dev.to. Read the complete article on the original site:

Read full article at Dev.to

More Gadgets & Consumer Tech