Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0

Client-Side WebP and AVIF Encoding Tradeoffs via Canvas.toBlob

Converting PNG and JPEG assets directly in the browser saves bandwidth and protects private documents from server-side storage. 1. Native HTMLCanvasElement.toBlob Support Modern Chromium and Firefox builds su

Converting PNG and JPEG assets directly in the browser saves bandwidth and protects private documents from server-side storage.

1. Native HTMLCanvasElement.toBlob Support

Modern Chromium and Firefox builds support image/webp natively via canvas.toBlob(cb, 'image/webp', quality). However, image/avif support varies across Safari and older mobile browsers, requiring a feature-detection check before falling back to a WASM encoder.

export async function encodeImage(canvas: HTMLCanvasElement, mime: string, quality = 0.85): Promise<Blob> {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (!blob) return reject(new Error('Encoding failed'));
      resolve(blob);
    }, mime, quality);
  });
}

2. Alpha Channel Preservation

When converting transparent PNG icons to WebP, avoid drawing onto an opaque background canvas; keep alpha: true on getContext('2d') so anti-aliased edges stay clean.

3. Reference Implementation

You can test zero-upload format conversion and image optimization on Alphaize Image Converter and Alphaize.

๐Ÿ“ฐ 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.