How to compress images on client-side

Optimizing images on the web is a common thing. For hellocurator, we want to optimize images before the upload, we can do it without servers, on the client-side.

The Canvas element let manipulate images with Javascript quite easily. We can found a lot of code examples about how to compress image with the Canvas API.

I will use compressorjs, a tiny librarie (3.8 kB minzipped). Compressor.js uses the Browser's native HTMLCanvasElement.toBlob() API to do the compression work, which means it is lossy compression.

There's a live Demo to play with it.

The code

In some case, I like to wrap dependencies in my projects. So the code looks like:


import Compressor from "compressorjs";
export const compress = async (
file: File,
quality: number,
maxHeight: number,
maxWidth: number,
convertSize?: number
): Promise<File | Blob> => {
return await new Promise((resolve, reject) => {
new Compressor(file, {
quality,
maxHeight,
maxWidth,
convertSize,
success: resolve,
error: reject,
});
});
};

You can use more options, as provided in the GitHub repo.

And, to use it


const upload async = (data) => {
const file = data.image[0];
const compressedFile = await compress(file, 0.6, 2000, 2000, 1000);
const imageUploaded = await upload(compressedFile);
...
}

GitHub Gist

Published: 4/7/2022

Join my newsletter to stay updated about the latest things I've created and discover the great finds I've come across on the internet.