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

We got tired of uploading files to convert them, so we moved the whole pipeline into a Web Worker

A few months ago, our team at MetalDevs needed to convert about thirty .heic photos from an iPhone to JPEGs and shrink a scanned PDF under 2 MB for an online form. Every tool on the first page of Google either capped us

A few months ago, our team at MetalDevs needed to convert about thirty .heic photos from an iPhone to JPEGs and shrink a scanned PDF under 2 MB for an online form. Every tool on the first page of Google either capped us at three files, made us wait on a slow upload bar, or wanted an email signup.

It felt ridiculous. Modern laptops sit right in front of us with 16 GB of RAM and multi-core CPUs, yet we were uploading private documents to some random Linux container just to run basic image compression.

So we decided to build the whole thing to run locally inside the browser tab. No S3 buckets, no backend queues, no file limits. Just Web Workers, OffscreenCanvas, and a couple of WebAssembly modules.

Getting a basic proof-of-concept working took an afternoon. Making it not crash on real-world batches of 50+ high-res photos took way longer. Here is what actually worked and where things broke.

Moving pixels off the main thread (and why bitmap.close() saved us)

Our first naive version used a standard '' on the main thread. That lasted about five minutesβ€”the second we dropped ten 4000Γ—3000 photos into the page, the entire UI froze solid until the loop finished.

The fix is moving the work into a dedicated Web Worker using OffscreenCanvas and createImageBitmap(). Instead of passing raw pixel arrays back and forth, you decode the file directly inside the worker:

// worker.js
self.onmessage = async (e) => {
  const { file, format, quality, targetWidth } = e.data;

  try {
    const bitmap = await createImageBitmap(file);

    const ratio = targetWidth && bitmap.width > targetWidth
      ? targetWidth / bitmap.width
      : 1;

    const w = Math.round(bitmap.width * ratio);
    const h = Math.round(bitmap.height * ratio);

    const canvas = new OffscreenCanvas(w, h);
    const ctx = canvas.getContext('2d');

    ctx.imageSmoothingEnabled = true;
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(bitmap, 0, 0, w, h);

    // Do NOT skip this line if you care about mobile browsers
    bitmap.close();

    const result = await canvas.convertToBlob({
      type: format,
      quality,
    });

    self.postMessage({ ok: true, blob: result });
  } catch (error) {
    self.postMessage({ ok: false, error: error.message });
  }
};

That bitmap.close() call looks harmless, but forgetting it caused our biggest headache during testing. Chrome's garbage collector doesn't always reclaim decoded GPU/bitmap memory fast enough when you're looping through a heavy batch. On a phone or an older laptop, the tab just silently dies mid-batch. Explicitly closing the bitmap the millisecond it hits the canvas keeps the memory footprint flat.

Hitting exact KB limits without guessing quality sliders

Most image compressors give you a 1–100 quality slider. Nobody actually wants to play a guessing game where you export at 75%, check Finder to see it's 240 KB, go back, drag it to 62%, and export again just because a portal demands "under 200 KB."

Since JPEG and WebP file sizes don't scale linearly with quality settings (a noisy photo of trees compresses completely differently than a clean UI screenshot), you can't just use a math formula to guess the right quality.
Instead, we wrote a quick binary search inside the worker that tests convertToBlob() until it lands right under the user's byte ceiling:

async function fitUnderByteLimit(canvas, mime, maxBytes) {
  let low = 0.05;
  let high = 0.95;
  let winner = null;

  // 7 steps gets us within ~0.7% precision without stalling the worker
  for (let step = 0; step < 7; step++) {
    const mid = (low + high) / 2;
    const candidate = await canvas.convertToBlob({ type: mime, quality: mid });

    if (candidate.size <= maxBytes) {
      winner = candidate;
      // Close enoughβ€”no need to burn extra CPU cycles
      if (candidate.size >= maxBytes * 0.94) break;
      low = mid;
    } else {
      high = mid;
    }
  }

  return winner;
}

One edge case we hit right away: if someone drops a massive 15 MB camera photo and asks for 50 KB, even quality: 0.05 won't get it small enough. When winner comes back null, the worker drops the canvas dimensions by 10% and runs the loop again until it fits.

We wired this up into PicsSizer so anyone can just type 100 KB or 200 KB and get the exact file on the first click.

Dealing with HEIC and PDFs via WebAssembly

createImageBitmap() handles JPEG, PNG, WebP, and AVIF out of the box, which covers 80% of use cases. The two formats that always break browser-only workflows are Apple's .heic photos and multi-page .pdf files.

For those, we compiled C/C++ decoders (libheif for HEIC and a lightweight PDF stream parser) to WebAssembly. The trick here is never loading the .wasm files upfrontβ€”nobody wants to download a 2 MB Wasm binary just to resize a quick PNG. We dynamically import the Wasm module only when a file header actually matches ftypheic *or *%PDF-.

For PDF compression, instead of turning every page into a giant image (which ruins selectable text and blows up file sizes), the parser walks the internal PDF object tree, pulls out the embedded raster scans, downsamples them on an OffscreenCanvas, and packs the stream back together.

If you want to test if it actually stays local, open PixConvert, pop open DevTools (F12 β†’ Network tab), and drop a file in. Once the page loads, network traffic stays completely flat at zero bytes.

Three small things we'd do differently from day one

  • Cap your worker pool: Early on we spawned a new Worker for every file dropped. On a 16-thread desktop, dropping 30 files spun up 30 workers at once and choked the browser. Capping a reusable pool at _Math.min(navigator.hardwareConcurrency || 4, 6) _made batch processing noticeably faster.
  • Clean up your Blob URLs: Every URL.createObjectURL() stays pinned in RAM until the tab closes. Call URL.revokeObjectURL() right after the download triggers.
  • Remember that Canvas strips EXIF data: Drawing onto a canvas wipes GPS tags and camera metadata automatically. For privacy tools that's a bonus, though it caught us off guard when testing photo orientation flags (EXIF Orientation).

Anyone else building local-first utilities with Wasm or OffscreenCanvas? Curious how you're handling Safari's quirks with worker canvas contextsβ€”it's been the trickiest browser to keep happy so far.

πŸ“° 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.