The Canvas API provides a straightforward browser-based solution. Developers can load images into an HTML image element. The browser then draws images onto a canvas. The canvas can export supported image formats. JPG output is available through toBlob().
async function convertAvifToJpg(file, quality = 0.9) {
const imageUrl = URL.createObjectURL(file);
try {
const image = new Image();
image.src = imageUrl;
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext("2d");
if (!context) {
throw new Error("Canvas is unavailable.");
}
context.drawImage(image, 0, 0);
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(
(result) => {
if (result) resolve(result);
else reject(new Error("JPG encoding failed."));
},
"image/jpeg",
quality
);
});
return blob;
} finally {
URL.revokeObjectURL(imageUrl);
}
}
This example assumes browser support for AVIF decoding. The quality argument typically ranges between zero and one. A value near 0.9 often provides useful quality. Actual output depends on browser encoding implementations. Canvas output also depends on available memory. Production applications should enforce reasonable image dimensions.
We can create AVIF to JPG converter using that.
Top comments (0)