Dev.to WebDev 🛠 Dev 👁 2 📖 5 min read

I Needed Image Tools That Don't Upload My Files Anywhere — So Here's How Client-Side Compression Works

The problem with "free" online image tools Most online image compressors work the same way: you upload a file, a server processes it, you download the result. That architecture is simple, but it has three costs that ar

The problem with "free" online image tools

Most online image compressors work the same way: you upload a file, a server processes it, you download the result. That architecture is simple, but it has three costs that are easy to overlook:

  1. Privacy. The files people compress are rarely holiday photos. They are ID cards, signed documents, payslips, certificates — exactly the files you least want sitting on a stranger's server, in a temp folder, under retention policies you will never read.
  2. Latency and cost. Uploading a 6MB photo on a slow connection just to get a 45KB file back is absurd, and someone pays for that bandwidth and compute on every single request.
  3. Trust. "We delete files after one hour" is a promise, not a mechanism. You cannot verify it.

The alternative is to do everything in the browser. Modern browsers ship with a surprisingly complete image-processing stack: the Canvas API for pixel manipulation, toBlob() for re-encoding, and libraries like Tesseract.js that can even run OCR in a Web Worker. This post walks through how a client-side "compress to exact KB" tool actually works, because the interesting part is not drawing the image to a canvas — it is hitting a precise byte target.

The naive approach, and why it fails

The obvious implementation is:

canvas.toBlob(callback, 'image/jpeg', 0.8);

Pick a quality, encode, done. This works fine if the goal is "smaller." It fails when the goal is "under 50KB, but as clear as possible" — which is the real-world requirement, because upload portals for exams, jobs and government forms reject anything over an exact limit.

The problem: there is no formula that maps quality to output bytes. The encoded size depends on the image's content. A quality of 0.8 might produce 900KB for a detailed photo and 40KB for a plain document scan. Quality is an input knob, not a size guarantee. So the tool has to search.

Binary search on quality

JPEG quality in the browser runs from 0 to 1. Encoded size is monotonic in quality — higher quality never produces a smaller file for the same image at the same dimensions. Monotonic functions are an invitation to binary search:

async function compressToTarget(img, targetBytes) {
  let lo = 0.05, hi = 0.95, best = null;
  for (let i = 0; i < 7; i++) {
    const mid = (lo + hi) / 2;
    const blob = await encode(img, mid);       // canvas.toBlob as a promise
    if (blob.size <= targetBytes) {
      best = blob;                             // fits — try better quality
      lo = mid;
    } else {
      hi = mid;                                // too big — lower quality
    }
  }
  return best;
}

Seven iterations narrow the quality range to under 1% of its span, which in practice lands within a few KB of the target. Each iteration is a full canvas encode, but even a 12-megapixel image encodes in tens of milliseconds on ordinary hardware, so the whole search feels instant. If even quality 0.05 overshoots the target, the fallback is to scale the image down (say, to 85% of its dimensions) and search again — dimensions and quality are two knobs, and using both beats crushing either one.

This is exactly the approach used by the tool this guide is based on: CompressKB runs this search locally for targets like 20KB or 100KB, and its reduce image size in KB page works the same way with a custom target. No file ever leaves the device — you can verify that claim in your browser's network tab, which is rather the point.

The gotchas nobody warns you about

EXIF orientation. Phone photos store rotation in EXIF metadata instead of rotating the pixels. Draw one to a canvas carelessly and it comes out sideways. createImageBitmap(file, { imageOrientation: 'from-image' }) handles it in modern browsers.

Metadata is data. A photo can carry GPS coordinates, device model and timestamps. When a tool re-encodes through canvas, the metadata is naturally dropped because only pixels are copied — which turns a side effect into a feature. A dedicated metadata remover does the same thing explicitly: draw, re-encode, download a file that contains the picture and nothing else.

PNG is the wrong tool for photos. PNG is lossless, so "compressing" a photo as PNG barely helps. Converting to JPEG (or WebP) is where the savings are. Conversely, never force screenshots with text through aggressive JPEG — the artefacts land exactly on the sharp edges. Format choice is part of the algorithm, not a user preference to ignore.

Colour profiles. Wide-gamut phone photos can look washed out after a canvas round-trip if the browser converts colour spaces inconsistently. For form-upload use cases nobody cares; for photography tools, test on real devices.

OCR without a server, briefly

The same "everything local" pattern extends further than compression. Tesseract.js compiles the Tesseract OCR engine to WebAssembly, so an image-to-text converter can extract text from a screenshot or scan in a worker thread with zero uploads. First run downloads the language data (a few MB, cacheable); after that, it is fully offline-capable. Performance will not beat a tuned server pipeline on huge batches, but for "pull the text out of this one document" it is more than good enough — and the document never leaves the machine.

When client-side is the wrong answer

Honesty section. Server-side processing still wins for: batch jobs with hundreds of files, formats the browser cannot decode (HEIC support is patchy), video (obviously), and anything needing guaranteed identical output across environments — browser JPEG encoders differ subtly. But for the everyday single-file tools — compress, resize, crop, convert, strip metadata, OCR a page — the browser is capable, instant, free to run, and private by architecture rather than by policy.

The takeaway

"Private by architecture" is a stronger claim than "we promise to delete your files," and for a whole category of small utilities it is now the easier claim to build. A canvas, a binary search over quality, and a bit of care with EXIF and formats gets you a tool that hits an exact 50KB target in milliseconds, works offline, and has no server to breach, bill, or trust. If you build utilities like this, make the network tab part of your demo — an empty Requests panel is the most convincing privacy policy there is.

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