Menu

Converting Images with the HTML Canvas API
📰

Converting Images with the HTML Canvas API

DEV Community: frontend·Amanda Jayathilaka·3 days ago
#lJhauutL
#devtofrontend#devto#dev#canvas#const
Reading 0:00
15s threshold

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;

Enter fullscreen mode

Exit fullscreen mode

} finally {

URL.revokeObjectURL(imageUrl);

}

}

This example assumes…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.