Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 3 min read

Hit an Exact KB Target in the Browser: Resizing Images With Canvas (No Server Upload)

Most image-resize code solves the easy half of the problem: get the file under a maximum size. Real upload forms are stricter than that. Exam and job portals routinely specify a band β€” a signature must be, say, 140Γ—60 px

Most image-resize code solves the easy half of the problem: get the file under a maximum size. Real upload forms are stricter than that. Exam and job portals routinely specify a band β€” a signature must be, say, 140Γ—60 px and between 10 KB and 20 KB. A thumb impression might be 560Γ—160 px and 20–50 KB. Too big is rejected. Too small is also rejected.

Landing inside a band, at exact pixel dimensions, entirely on the client, is a fun little engineering problem. Here's the pipeline I use.

Step 1: Decode with orientation fixed

Phone photos carry EXIF orientation. If you draw one to a canvas naively, it can come out rotated. createImageBitmap with imageOrientation: 'from-image' handles it in modern browsers:

const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });

Step 2: Draw to the exact pixel size

Portals check pixel dimensions exactly β€” 200Γ—230 means 200Γ—230, not "about that". So the canvas is the spec:

const canvas = document.createElement('canvas');
canvas.width = 560;   // spec width, px
canvas.height = 160;  // spec height, px
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';            // signatures/photos sit on white
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);

(For a real signature you'd crop to the ink bounding box first and centre it β€” the point here is the encode step.)

Step 3: Binary-search the JPEG quality until the size lands in-band

canvas.toBlob takes a quality parameter for JPEG. File size rises monotonically with quality, which makes it a textbook binary search:

async function encodeInBand(canvas, minBytes, maxBytes) {
  let lo = 0.05, hi = 1.0, best = null;
  for (let i = 0; i < 7; i++) {
    const q = (lo + hi) / 2;
    const blob = await new Promise(r => canvas.toBlob(r, 'image/jpeg', q));
    if (blob.size > maxBytes) {
      hi = q;              // too heavy β€” lower the quality
    } else if (blob.size < minBytes) {
      lo = q;              // too light β€” raise it, remember this candidate
      best = blob;
    } else {
      return blob;         // inside the band
    }
  }
  return best;             // closest attempt that stays under the ceiling
}

Seven iterations get you within ~1% of the quality range β€” more than enough, and each toBlob on a small canvas is a few milliseconds. No server round-trip, no upload, the file never leaves the device.

Step 4: Respect the floor problem

Here's the part nobody warns you about: a minimum-KB floor can be physically hard to reach. A mostly-white signature on a small canvas is extremely compressible β€” at 140Γ—60 px, even quality 1.0 may produce only a few KB, because there's simply very little information in the image. Raising quality past that point adds nothing; the encoder has nothing left to spend bytes on.

At larger canvases the band is comfortable (560Γ—160 px at high quality lands naturally in a 20–50 KB window). At tiny ones, if the portal's validator truly enforces its printed floor, no honest re-encode of the same pixels will satisfy it β€” which is why so many applicants see "file too small" errors on signatures they've done nothing wrong with. Knowing this saves you from shipping a "compressor" that promises a band it can't always hit.

Step 5: Two spec-sheet traps

  • DPI is (mostly) a red herring. Notifications print "200 dpi" next to pixel dimensions, but validators check pixels and bytes. The JFIF density field in the file header changes neither. If a portal asks for 200Γ—230 px at 200 dpi, it is asking for 200Γ—230 px.
  • Format is not a free choice. PNG on a photograph explodes past any KB ceiling; JPEG on line art stays tiny. Every spec I've seen for these portals means JPEG, whether or not it says so in as many words.

Putting it together

Decode with orientation β†’ draw at exact spec pixels β†’ binary-search quality into the KB band β†’ be honest about floors. That pipeline powers the signature and photo presets in SignResize, a free tool I built for exam applicants β€” it runs 100% in the browser, because the last thing a personal document should need is a trip to someone else's server.

If you're building an upload flow with size bands, steal the binary search. It's about fifteen lines, and it's the difference between "compressed" and "accepted".

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.