DEV Community

Azqora Tech
Azqora Tech

Posted on

Compress an image to a target file size in the browser with the Canvas API

Many forms ask for a photo under a fixed size, such as 50 KB or 200 KB. You can do this fully in the browser, without uploading the file anywhere. The idea is simple: draw the image on a canvas, export it as JPEG with a quality value, and search for the highest quality that still fits the limit.

Step 1: Draw the image on a canvas

async function loadToCanvas(file, maxWidth) {
  const bitmap = await createImageBitmap(file);
  const scale = Math.min(1, maxWidth / bitmap.width);
  const canvas = document.createElement("canvas");
  canvas.width = Math.round(bitmap.width * scale);
  canvas.height = Math.round(bitmap.height * scale);
  canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height);
  return canvas;
}
Enter fullscreen mode Exit fullscreen mode

Reducing the pixel size first is the biggest saving. A 4000 px wide phone photo is far larger than any form needs.

Step 2: Export with a quality value

function toBlob(canvas, quality) {
  return new Promise((resolve) =>
    canvas.toBlob(resolve, "image/jpeg", quality)
  );
}
Enter fullscreen mode Exit fullscreen mode

The quality argument is a number from 0 to 1. It applies to lossy formats such as JPEG and WebP. PNG is lossless, so the quality value has no effect on it.

Step 3: Binary search the quality

File size does not change in a perfectly smooth way, so searching is better than guessing.

async function compressToLimit(canvas, limitBytes) {
  let low = 0.1;
  let high = 0.95;
  let best = null;
  for (let i = 0; i < 8; i++) {
    const mid = (low + high) / 2;
    const blob = await toBlob(canvas, mid);
    if (blob.size <= limitBytes) {
      best = blob;
      low = mid;
    } else {
      high = mid;
    }
  }
  return best;
}
Enter fullscreen mode Exit fullscreen mode

If best is still null after the loop, even the lowest quality is too large. Shrink the canvas a little and run the search again.

Things to watch

  • Transparency: JPEG has no alpha channel. Fill the canvas with white before drawing if the image has transparent areas.
  • EXIF rotation: modern browsers apply orientation when you decode with createImageBitmap, but check with a photo taken in portrait mode.
  • Very small limits: below roughly 20 KB, lower the pixel size instead of pushing quality to the minimum, or the image will look blocky.
  • Privacy: nothing here needs a server, so the photo never leaves the device.

Disclosure: I work on PixelKaro, a set of free browser-based image and PDF tools (https://pixelkaro.com) that process files on your device. The code above is a simplified example of the general approach, not a copy of how any specific tool is built.

Top comments (1)

Collapse
 
komopdf profile image
KomoPDF •

The search never tests quality 0.1 itself, so best can stay null even when the image would fit at the lower bound. Try that endpoint before reducing dimensions. Also handle a null result from canvas.toBlob(), which can fail to encode.