DEV Community

ToeMarketing
ToeMarketing

Posted on Originally published at theoryofeverything.co.in

Client-Side Image Compression to 20KB & 50KB in Pure Browser JavaScript (Canvas API Binary Search)

Students and job applicants in India routinely hit strict file-size rules when uploading passport photos and signatures to portals like SSC MTS, UPSC, CUET UG, IBPS, and NEET—often under 20KB, 50KB, or 100KB in JPEG format.

Most online compressors upload your personal ID images to a third-party server. Here is how to build—or use—a 100% browser-side compressor using the HTML5 Canvas API with binary search on JPEG quality.


Why Binary Search Beats Fixed Quality Compression

Setting a hardcoded JPEG quality like 0.7 fails unpredictably:

  • A clean portrait photo might stay 95KB (rejected by a 50KB form limit).
  • Or compress down to 14KB and fail readability checks.

Instead, running a 6-step binary search between quality = 0.1 and quality = 0.95 converges cleanly on the highest visual clarity that still stays below your target byte budget:

async function compressToTargetKB(canvas, targetKB) {
  const maxBytes = targetKB * 1024;
  let low = 0.08;
  let high = 0.95;
  let bestBlob = null;

  for (let i = 0; i < 7; i++) {
    const mid = (low + high) / 2;
    const blob = await new Promise((resolve) =>
      canvas.toBlob(resolve, "image/jpeg", mid)
    );
    if (blob.size <= maxBytes) {
      bestBlob = blob;
      low = mid; // try higher visual quality
    } else {
      high = mid; // shrink further
    }
  }
  return bestBlob;
}
Enter fullscreen mode Exit fullscreen mode

Live Zero-Upload Utility & Exam Guides

Top comments (0)