Convert HEIC to WebP in the Browser with JavaScript


HEIC (High-Efficiency Image Coding) files are commonly used by Apple devices for storing photos. However, these files are not always easily accessible or shareable due to compatibility issues. Converting HEIC images to a more universally accepted format like WebP can be highly beneficial. In this article, we will learn how to convert HEIC files to WebP directly in the browser environment if you know a bit of JavaScript.
Why Convert HEIC to WebP?
Compatibility: WebP is supported by most modern web browsers and offers excellent compression and quality.
Preservation of Quality: WebP ensures high-quality image rendering with efficient compression.
Ease of Sharing: WebP files are smaller in size compared to other formats like JPEG and PNG, making them easier to share.
Privacy: Converting files directly in the browser ensures that your data stays on your device, protecting your privacy. With AI, all data is used to train models, so your data is not safe on other servers.
Overview of the Code
Our solution involves four main steps:
Load the HEIC File
Convert HEIC to an Image Format (PNG)
Convert PNG to WebP
Download the WebP Images
Step 1: Load the HEIC File
We start by creating a file input element in HTML to allow users to select HEIC files from their device. This input element is designed to accept multiple files at once and restricts the file types to those with a .heic extension.
<input type="file" id="fileInput" accept=".heic" multiple />
Step 2: Convert HEIC to an Image Format (PNG)
To convert HEIC files to PNG, we utilize the heic2any
library. This library can handle the conversion of HEIC files to various formats, including PNG, JPEG, GIF but it cannot change directly to WEBP
. So, we define an asynchronous function, convertHeicToPng
, which takes a file as input and returns a blob of the converted image to PNG
as output which we can further convert to webp.
import heic2any from 'heic2any';
async function convertHeicToPng(file) {
const blob = await heic2any({ blob: file, toType: 'image/png' });
return blob;
}
Step 3: Convert PNG to WebP
In this step, we convert the PNG image (resulting from the HEIC conversion) to a WebP image using the canvas element in the browser. Here's a detailed breakdown of the process:
Creating the convertToWebp
Function
We define an asynchronous function, convertToWebp
, which takes an array of HEIC files as input. This function handles the conversion of each file from HEIC to PNG, and then from PNG to WebP.
async function convertToWebp(files) {
const imageBlobPromises = files.map((file) => {
return new Promise((resolve, reject) => {
convertHeicToPng(file).then((blob) => {
Creating Object URLs for Blobs
Once we have the PNG blob from the convertHeicToPng
function, we create an object URL for this blob. This URL can be used as the source for an Image
object. Working with blobs can be challenging, so we convert it to an object URL. This allows us to set it as the image source, enabling us to hook into browser image creation functionality.
const imageBlobUrl = URL.createObjectURL(blob);
Loading the Image
We create a new blank Image
object and whenever this image is loaded and it have a src we want to perform certain function on it which will be done by img.onload
this allows us to pass a callback whenever an image loads its source image.
const img = new Image();
img.onload = () => {
Drawing Image onto Canvas
We create a canvas element and set its dimensions to match those of the loaded image. Then, we get the 2D drawing context of the canvas and draw the image onto the canvas using the drawImage
method.
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0);
Converting Canvas to WebP Blob
We convert the image drawn on the canvas to a WebP blob using the toBlob
method. Here we first create a new image when we draw onto the canvas after taht we can save into the desired filetype. The toBlob
method takes a callback function that receives the resulting blob. We set the image format to 'image/webp' and specify the quality (0.8 in this case) you can change it according to what you want better set it as a parameter that can be given in your app.
canvas.toBlob(
(blob) => {
if (blob) {
const webpUrl = URL.createObjectURL(blob);
resolve({
url: webpUrl,
name: `image_${files.indexOf(file) + 1}.webp`,
});
} else {
reject(new Error('Blob conversion failed'));
}
},
'image/webp',
0.8
);
};
Handling Errors
We handle any errors that occur during the image loading process by rejecting the promise. Start the entire process of converting the imahe
img.onerror = reject;
img.src = imageBlobUrl;
}).catch(reject);
});
});
const imageBlobUrls = await Promise.all(imageBlobPromises);
return imageBlobUrls;
}
Full Code for Step 3
Here’s the complete code for the convertToWebp
function:
javascriptCopy codeasync function convertToWebp(files) {
const imageBlobPromises = files.map((file) => {
return new Promise((resolve, reject) => {
convertHeicToPng(file).then((blob) => {
const imageBlobUrl = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0);
canvas.toBlob(
(blob) => {
if (blob) {
const webpUrl = URL.createObjectURL(blob);
resolve({
url: webpUrl,
name: `image_${files.indexOf(file) + 1}.webp`,
});
} else {
reject(new Error('Blob conversion failed'));
}
},
'image/webp',
0.8
);
};
img.onerror = reject;
img.src = imageBlobUrl;
}).catch(reject);
});
});
const imageBlobUrls = await Promise.all(imageBlobPromises);
return imageBlobUrls;
}
By following these detailed steps, you can effectively convert HEIC images to WebP format directly in the browser, ensuring compatibility and efficient image compression.
Step 4: Download the WebP Images
In the final step, we provide functionality for the user to download the generated WebP images.
Creating the Download Function
We define an asynchronous function downloadWebp
that takes the selected files as input.
async function downloadWebp(files) {
const webpImages = await convertToWebp(files);
webpImages.forEach((image) => {
const a = document.createElement('a');
a.href = image.url;
a.download = image.name;
a.click();
URL.revokeObjectURL(image.url);
});
}
Adding Event Listener to File Input
We add an event listener to the file input element to call the downloadWebp
function whenever files are selected.
document.getElementById('fileInput').addEventListener('change', (event) => {
const files = Array.from(event.target.files);
downloadWebp(files);
});
Conclusion
Converting HEIC files to WebP directly in the browser is a practical solution for overcoming compatibility issues and ensuring high-quality image rendering with efficient compression. By following the steps outlined in this article, you can easily convert and share your HEIC images in a universally accepted format. For a seamless and efficient conversion process, you can also visit our website, onlineheicconvert.com, where I have implemented this functionality so that you can convert HEIC files with full privacy.
Subscribe to my newsletter
Read articles from HEIC Converter directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
