An image compressor doesn't need a server to receive the original file. On Wezual Tools, we use browser APIs to decode the image, resize it when requested, and encode a new file. The original image stays on the device during compression.
Decode, draw, and encode
The input is a browser File. After decoding the image, we draw it onto a canvas sized for the output. If the user sets a maximum width, we scale down while preserving the aspect ratio. This can reduce the output size before we adjust quality.
Canvas encoding is asynchronous. We check the returned MIME type because a browser can fall back to another format when it can't encode the requested one.
function encode(canvas, type, quality) {
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob?.type !== type) {
reject(new Error("This browser cannot encode the selected format."));
return;
}
resolve(blob);
}, type, quality);
});
}
Treat a size limit as a measurement
A quality setting is an input to the encoder. It doesn't predict a file size. For size targets, we encode at candidate quality settings and inspect each resulting Blob's byte length. If a file can't meet the chosen limit at those settings, reducing its pixel dimensions or switching to a lossy format can help. PNG doesn't respond to the quality slider like JPEG or WebP does.
Test more than the happy path
Try a large photo, a transparent PNG, and a batch of files. Compare the output type, dimensions, and byte size. Be explicit about transparency when exporting to JPEG, which has no alpha channel. Large images also deserve attention because decoding consumes memory based on pixel dimensions even when the input file is small.
You can try this workflow in the Wezual Image Compressor. I'm sharing it as part of the team behind Wezual Tools.
Top comments (0)