DEV Community

黃彥鈞
黃彥鈞

Posted on

Build a Zero-Server Batch Image-to-WebP Compressor in Pure Browser JavaScript

Every time you upload screenshots or client brand assets to a free online image compressor, your files travel to a third-party server. The funny part? Modern browsers already ship with native hardware-accelerated WebP encoding via the HTML5 Canvas API.

How Browser-Side WebP Compression Works

You can convert PNG/JPEG files to lightweight .webp completely offline in fewer than 30 lines of TypeScript:

export async function convertToWebP(file: File, quality = 0.82): Promise<Blob> {
  const bitmap = await createImageBitmap(file);
  const canvas = document.createElement('canvas');
  canvas.width = bitmap.width;
  canvas.height = bitmap.height;

  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('Canvas 2D context unavailable');
  ctx.drawImage(bitmap, 0, 0);

  return new Promise((resolve, reject) => {
    canvas.toBlob(
      (blob) => (blob ? resolve(blob) : reject(new Error('WebP encoding failed'))),
      'image/webp',
      quality
    );
  });
}
Enter fullscreen mode Exit fullscreen mode

Why createImageBitmap Beats new Image()

  • Decodes images off the main thread when supported, preventing UI jank during batch conversion.
  • Handles EXIF orientation cleanly in modern Chromium, Firefox, and Safari.
  • Works seamlessly with drag-and-drop multiple files without touching any backend or S3 bucket.

Try the Ready-Made Zero-Upload Tool

If you just want to drag-and-drop images and compress them locally right now (with quality slider and instant KB savings preview), you can use the free browser tool I shipped on CostLens:

Typical savings on PNG UI screenshots are 65% to 85% with visually identical quality at 0.82.

Top comments (0)