Client-Side Image Compression & Conversion: WebP, AVIF & HTML5 Canvas
How to compress, resize, and convert modern image formats in the browser without uploading binary assets to external servers.

1. The Impact of Image Payloads on Core Web Vitals
Images account for over 60% of average website byte transfers. Uncompressed JPEG and PNG uploads directly hurt Largest Contentful Paint (LCP) scores and increase mobile bounce rates.
Modern image formats like WebP and AVIF deliver 30% to 50% better compression ratios than legacy JPEG while preserving visual fidelity.
2. Zero-Upload Compression Using HTML5 Canvas
Traditionally, web applications uploaded user photos to backend server instances running ImageMagick or Sharp. This approach exposes private user imagery to server storage and consumes substantial bandwidth.
Using modern browser APIs, we can decode images via `createImageBitmap` and draw them onto an offscreen canvas. We can then export optimized WebP or JPEG blobs locally using `canvas.toBlob()`.
export async function compressImageClient(
file: File,
quality: number = 0.8,
maxWidth: number = 1920
): Promise<Blob> {
const bitmap = await createImageBitmap(file);
const ratio = Math.min(maxWidth / bitmap.width, 1);
const width = Math.round(bitmap.width * ratio);
const height = Math.round(bitmap.height * ratio);
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Canvas context initialization failed");
ctx.drawImage(bitmap, 0, 0, width, height);
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (blob) resolve(blob);
else reject(new Error("Image conversion failed"));
},
"image/webp",
quality
);
});
}3. Privacy Benefits of Local Conversion
Processing media locally guarantees that sensitive photos, ID scans, or company documents never leave the visitor's machine. This guarantees zero compliance exposure under GDPR and HIPAA.