How to Compress an Image to an Exact KB Size in JavaScript (Binary Search Over canvas.toBlob)

Learn how to compress photos to exact kilobyte limits using client-side binary search quantization over canvas.toBlob, with adaptive dimension downscaling fallback.

How to Compress an Image to an Exact KB Size in JavaScript (Binary Search Over canvas.toBlob)
Table of Contents
Key Takeaways
  • Most compression tools expose a 1 to 100 quality percentage slider, forcing users into trial-and-error to meet strict file limits.
  • Because Discrete Cosine Transform (DCT) efficiency varies with visual entropy, 70% quality might yield 45 KB on a portrait but 180 KB on a detailed document.
  • Running a binary search loop over canvas.toBlob(callback, 'image/jpeg', quality) converges within 2 KB of an exact target kilobyte budget in 6 to 8 iterations.
  • When transcoding transparent PNGs to JPEG, browsers default undefined alpha pixels to black; composite onto an opaque white background first.
  • When extreme targets hit JPEG's minimum quantization floor, an adaptive 10% dimension downscaling loop breaks through the ceiling.
  • PoofShare executes this entire binary search and dimension downscaling pipeline in browser RAM inside our standalone Exact Target-KB Image Compressor.

The Engineering Problem: Rigid Portal Kilobyte Ceilings

Every week, applicants encounter strict upload limits on government visa systems, university portals, and job application forms: "File size must not exceed 50 KB."

These portals reject submissions exceeding the ceiling by even a single byte. To comply, users turn to compressors with vague "Quality: 1% to 100%" sliders, trapped in trial-and-error: export at 75% (rejected); re-export at 60% (rejected); re-export at 45% (accepted, but blurry).

Commercial sites offering exact KB targeting often paywall the feature or upload sensitive IDs to cloud servers, risking identity theft and violating the zero-knowledge model in our Privacy Policy.

In this guide, we explore building an exact-KB client-side compression engine in JavaScript using HTML5 Canvas, binary search bisection, and adaptive downscaling.

Why Quality Percentages Do Not Map Linearly to File Size

Static quality sliders fail because of how lossy JPEG compression operates.

JPEG divides images into 8x8 pixel blocks, transforms spatial data into frequency coefficients using the Discrete Cosine Transform (DCT), and quantizes high frequencies using a quantization matrix.

Because images exhibit different visual entropy, identical quality values yield wildly different byte sizes:

Soft Portrait Photo (1920x1080):
  Quality 0.85 -> 180 KB | Quality 0.45 ->  46 KB (Fits under 50 KB)

Dense Document Scan (1920x1080):
  Quality 0.85 -> 480 KB | Quality 0.45 -> 165 KB (Exceeds 50 KB by 230%)

Photos with high-frequency details (fine text, fabric textures) contain numerous non-zero DCT coefficients that compress poorly. Conversely, smooth images compress rapidly. Predicting exact file size from a slider is mathematically impossible without inspecting encoded output bytes.

The Alpha Channel Trap: Compositing Transparent PNGs

When processing images in browser memory, developers must avoid transparent alpha pixel blackening.

Document scans and signature crops are often transparent 32-bit PNGs. Standard JPEG lacks alpha channel support. Drawing a transparent PNG onto an uninitialized canvas and calling canvas.toBlob(cb, 'image/jpeg') causes browsers to default transparent pixels to solid black (#000000), turning transparent signatures into black rectangles.

To fix this, composite over an opaque white background (#ffffff) first:

const canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');

ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(sourceImage, 0, 0, targetWidth, targetHeight);

An opaque white foundation ensures transparent PNGs and scans convert cleanly to JPEG without visual corruption.

The 7-Step Binary Search Convergence Algorithm

Between quality 0.05 and 0.95, JPEG file size is strictly monotonic: higher quality increases bytes; lower quality decreases bytes. This property enables fast binary search bisection.

Binary Search Convergence Loop Over canvas.toBlob
Binary Search Convergence Loop Over canvas.toBlob

The algorithm executes across seven phases:

  1. Ingestion: Load the source image into an ImageBitmap and set targetBytes = targetKB * 1024.
  2. Boundary Setup: Initialize low = 0.05 and high = 0.95.
  3. Probing: If quality = 0.95 blob ≤ targetBytes, exit immediately. If quality = 0.05 blob > targetBytes, trigger dimension downscaling.
  4. Midpoint Encoding: Compute mid = (low + high) / 2 and call canvas.toBlob(resolve, 'image/jpeg', mid).
  5. Evaluation: If blob.size > targetBytes, set high = mid. If blob.size <= targetBytes, record bestBlob = blob and set low = mid.
  6. Termination: Exit if blob.size lands between 95% and 100% of target, (high - low) < 0.01, or iterations hit 8 passes.
  7. Export: Deliver bestBlob for download or stage into our zero-log temporary uploader.

Real-World Convergence Trace: Benchmarking 7 Iterations

Here is our algorithm running on a 2.41 MB smartphone portrait (2400 x 1800) targeting a strict 50 KB ceiling:

IterationQualityOutput SizeDelta vs. 50 KBElapsedAction Taken
Baseline0.95486.2 KB+436.2 KB28 msExceeds budget; enter loop
Iter 10.50078.4 KB+28.4 KB18 msToo large; high = 0.500
Iter 20.27541.2 KB-8.8 KB16 msFits budget; low = 0.275
Iter 30.38756.1 KB+6.1 KB17 msToo large; high = 0.387
Iter 40.33147.9 KB-2.1 KB15 msFits budget; low = 0.331
Iter 50.35951.8 KB+1.8 KB16 msToo large; high = 0.359
Iter 60.34549.3 KB-0.7 KB15 msFits budget; early exit
Result0.34549.3 KB-0.7 KB125 msSuccess in 6 iterations

In six passes taking 125 milliseconds in browser RAM, the engine landed at 49.3 KB (98.6% capacity) without overshooting.

TIP
Why Cap Iterations at 8 Passes: Beyond 7 to 8 iterations, quality adjustments change file sizes by fewer than 200 bytes. Capping iterations at 8 guarantees execution finishes in under 200 ms while avoiding mobile battery drain.

Adaptive Dimension Downscaling: Breaking Through the Floor

When compressing a 12-megapixel photo down to 20 KB, JPEG hits an absolute mathematical floor. Even at quality 0.05, JPEG binary structures require baseline byte overhead:

  • Start of Image (SOI) and End of Image (EOI) markers
  • APP0 / JFIF headers and color space metadata
  • Huffman coding entropy trees (DHT) and Quantization tables (DQT)
  • Baseline 8x8 DCT blocks across 12 million pixels
JPEG Quality vs. File Size Non-Linearity and Dimension Fallback
JPEG Quality vs. File Size Non-Linearity and Dimension Fallback

For large photos, this floor sits between 30 KB and 45 KB. When our engine detects that quality = 0.05 exceeds targetBytes, it automatically triggers an adaptive dimension downscaling loop.

Stepping down dimensions by 10% geometrically (scale *= 0.90) reduces total pixel volume by approximately 19% on each step. This rapidly lowers the baseline DCT payload without creating aspect ratio distortion, keeping passport facial features and signatures crisp.

Complete In-Browser JavaScript Implementation

Here is the complete implementation you can run directly inside any modern browser environment:

export async function compressToExactKB(sourceImage, targetKB, maxIter = 8) {
  const targetBytes = targetKB * 1024;
  const origW = sourceImage.naturalWidth || sourceImage.width;
  const origH = sourceImage.naturalHeight || sourceImage.height;
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  let scale = 1.0;

  const toBlob = q => new Promise(r => canvas.toBlob(r, 'image/jpeg', q));

  for (let step = 0; step < 10; step++) {
    const w = Math.max(16, Math.round(origW * scale));
    const h = Math.max(16, Math.round(origH * scale));
    canvas.width = w; canvas.height = h;
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, w, h);
    ctx.drawImage(sourceImage, 0, 0, w, h);

    const minBlob = await toBlob(0.05);
    if (minBlob.size > targetBytes) {
      scale *= 0.90;
      continue;
    }

    const maxBlob = await toBlob(0.95);
    if (maxBlob.size <= targetBytes) return { blob: maxBlob, width: w, height: h };

    let low = 0.05, high = 0.95, best = minBlob;
    for (let i = 0; i < maxIter && (high - low) > 0.01; i++) {
      const mid = (low + high) / 2;
      const b = await toBlob(mid);
      if (b.size <= targetBytes) {
        best = b; low = mid;
        if (b.size >= targetBytes * 0.98) break;
      } else {
        high = mid;
      }
    }
    return { blob: best, width: w, height: h };
  }
}

Zero-Knowledge Privacy Architecture

Handling passport photos and identity documents demands rigorous data privacy. At PoofShare, our tools execute 100% locally:

  • Pure Browser Execution: Zero image buffers traverse the network during quantization.
  • Ephemeral Sharing: Click "Share via Expiring Link" to dispatch compressed files via our zero-log temporary uploader, where files self-destruct upon expiration.
  • Verification Lightbox: Our integrated side-by-side zoom inspector allows inspecting fine text and passport outlines at up to 4x magnification before saving.

Review our architectural commitments in our Privacy Policy and About Page.

Try the live tool now: launch our free Exact Target-KB Image Compressor to shrink your photos to 20 KB, 50 KB, 100 KB, or custom limits in seconds.

Why does this algorithm use binary search instead of calculating quality directly?

JPEG compression efficiency depends on visual frequency and entropy across image blocks. Because this relationship is non-linear and varies between photos, there is no closed-form formula to compute file size from pixel dimensions. Binary search converges on the optimal quality setting in fractions of a second.

How does compositing on white prevent transparent PNGs from turning black?

JPEG has no native alpha channel. When drawing transparent pixels to a canvas and exporting to JPEG, browsers default transparent regions to black. Filling the canvas with opaque white (#ffffff) before drawing the image guarantees transparent backgrounds convert seamlessly into clean white space.

What is the minimum achievable file size for a high-resolution photo?

Every JPEG file requires header markers (SOI, APP0, DQT, DHT, SOF0) and baseline macroblocks that consume 25 KB to 40 KB for multi-megapixel photos even at quality 0.05. When targets fall below this floor, adaptive dimension downscaling reduces resolution by 10% steps until the byte budget is satisfied.

Can this client-side algorithm process HEIC and WebP inputs?

Yes. Modern browsers decode JPEG, PNG, WebP, and supported HEIC files into native ImageBitmap buffers. The canvas draws the raster pixels and re-encodes the output stream into universally compatible JPEG format.

PS

PoofShare Team

Dedicated to building zero-knowledge, ephemeral hosting systems and sharing practical technical guides on privacy.

Link copied to clipboard!