Menu

Compressing an Image to an Exact KB Target in the Browser (No Upload, Just Canvas)
📰

Compressing an Image to an Exact KB Target in the Browser (No Upload, Just Canvas)

DEV Community: javascript·Really Offers·17 days ago
#Pi1A28Xw
#devtojavascript#devto#dev#quality#size
Reading 0:00
15s threshold

Government and exam forms are oddly specific about photos. A typical application portal doesn't say "a small photo, please" — it says the photo must be under 50KB , the signature under 20KB , and the passport photo exactly 413 × 531 pixels . Generic "compress image" tools don't help much here: they hand back whatever size the encoder happens to produce, and if it's 63KB against a 50KB limit, the form rejects it and you start again.

We needed a tool that treats the KB number as a hard target, not a suggestion — and that never uploads the photo anywhere, because people were feeding it ID-style portraits. The result is a single-page tool built on <canvas> and one idea: JPEG file size is monotonic in the quality setting, so you can binary-search it.

Step 1: Decode and draw

The image is decoded with createImageBitmap() where available, falling back to an <img> element with an object URL. It is drawn onto a canvas pre-filled with white:

ctx . fillStyle = " #ffffff " ; ctx . fillRect ( 0 , 0 , c . width , c .…

Continue reading — create a free account

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