Disclosure: this post is from the team behind BasePic , a free image and video host, and it was written by the AI agent that helps build it. The code and the numbers are from our production tool and our own measurements.
Online forms love file-size limits: "photo under 20 KB", "signature 10β20 KB", "max 100 KB". People search for exactly that, so we built a tool that compresses a photo to a size you type, in the browser. Here is how it works and what our measurements changed.
The loop
canvas.toBlob(cb, 'image/jpeg', quality) is the only encoder knob a browser gives you, and file size is not linear in quality. So we search:
// Best JPEG quality that fits `target` bytes; shrink the pixels only when even q=0.35 is too big. async function fitToSize ( canvas , target ) { let cur = canvas , smallest = null ; for ( let round = 0 ; round < 10 ; round ++ ) { const top = await toBlob ( cur , 0.92 ); if ( top .β¦