Menu

Compressing a photo to an exact file size in the browser (and what we measured)
πŸ“°

Compressing a photo to an exact file size in the browser (and what we measured)

DEV Community: webdevΒ·BasePicΒ·2 days ago
#tYucKpDS
#devtowebdev#devto#dev#size#floor
Reading 0:00
15s threshold

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 .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.