DEV Community

Jalal khan
Jalal khan

Posted on

Compress Images in the Browser with Canvas API — No Uploads, No Server

Most online image compressors upload your file to a server. This one runs entirely in the browser using the native Canvas API — no uploads, no watermark, no signup. You can try it live here: https://yourutilityhub.com/image/image-compressor

Why compress images in the browser?

  • No uploads — your photos never leave your device
  • No watermark or signup
  • Instant — no server round-trip
  • Works with PNG, JPG, and WEBP

The core idea

Draw the image onto an invisible <canvas>, then export it with a lower quality setting using canvas.toBlob(). The browser does the heavy lifting — no libraries needed.

1. Read the file into an object URL

const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  const selectedFile = e.target.files?.[0];
  if (selectedFile && selectedFile.type.startsWith("image/")) {
    setFile(selectedFile);
    setOriginalSize(selectedFile.size);
    setOriginalUrl(URL.createObjectURL(selectedFile));
  }
};
Enter fullscreen mode Exit fullscreen mode

URL.createObjectURL() gives us a local blob URL — the file never leaves the browser.

2. Load the image and draw it on a canvas

const img = new Image();
img.onload = () => {
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d");
  if (ctx) {
    ctx.drawImage(img, 0, 0);

    canvas.toBlob(
      (blob) => {
        if (blob) {
          setCompressedUrl(URL.createObjectURL(blob));
          setCompressedSize(blob.size);
        }
      },
      file.type,       // keep original format (jpg, png, webp)
      quality[0] / 100 // 0.0 – 1.0
    );
  }
};
img.src = originalUrl;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)