Compressing a digital photo to an exact file size requires adjusting both the compression quality factor and the pixel dimensions. Our local engine starts by drawing your uploaded image onto an offscreen canvas. It then runs an iterative optimization search, adjusting the lossy compression ratio (quality) to output a file as close to your target as possible.
// Iterative quality search on HTML Canvas
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
// Adjust quality factor (0.1 to 0.95)
canvas.toBlob((blob) => {
console.log("Size in bytes:", blob.size);
}, "image/jpeg", quality);