Converting HEIC to JPG in the browser: why canvas alone fails in Chrome
iPhones save photos as HEIC. Safari can show them. Chrome, Edge and Firefox cannot. If you build an image tool that draws an uploaded file to a canvas, HEIC files fail with no useful error.
I hit this while fixing the HEIC to JPG converter on a free tool site. The page looked fine, but on Chrome the preview never loaded and nothing was converted.
What goes wrong
The usual browser path is:
- Read the file.
- Put it in an
<img>through an object URL. - Draw it to a canvas.
- Call
canvas.toBlob('image/jpeg').
Step 2 is where HEIC dies in Chrome. The <img> fires onerror, because the browser has no decoder for the format.
The fix
Decode the file yourself, then hand the browser a format it understands. The heic-to package wraps libheif and runs in the browser, so the photo never leaves the device.
// Resolves with an object URL only if the browser can display the blob.
const displayableUrl = (blob: Blob): Promise<string> => new Promise((resolve, reject) => {
const url = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => resolve(url);
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Cannot display image'));
};
img.src = url;
});
async function loadPreview(file: File, isHeic: boolean): Promise<string> {
try {
return await displayableUrl(file); // Safari, and every normal image
} catch (err) {
if (!isHeic) throw err;
const { heicTo } = await import('heic-to'); // loaded only when needed
return displayableUrl(await heicTo({ blob: file, type: 'image/png' }));
}
}
Two details matter. Try the native path first. Safari can display HEIC, and normal JPG and PNG files never need libheif. You only pay for the decoder when you have to.
Load the library lazily. libheif is large. A dynamic import() keeps it out of the main bundle, so the page stays fast for people who never upload a HEIC.
Detecting HEIC without trusting the extension
Some files arrive with the wrong name or no type. Check the file header instead. HEIC and HEIF files have ftyp at byte 4, followed by a brand such as heic, heix, hevc, hevx, mif1 or msf1.
const bytes = new Uint8Array(await file.slice(0, 12).arrayBuffer());
const isFtyp = bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70;
const brand = String.fromCharCode(...bytes.slice(8, 12));
const isHeic = isFtyp && ['heic', 'heix', 'hevc', 'hevx', 'mif1', 'msf1'].includes(brand);
Memory
Decoding a large photo takes real memory. If a user drops 20 photos at once, decode them one at a time, not all together, so memory use stays low.
Try it
The result is live as a free tool: HEIC to JPG converter. It runs in your browser and needs no sign-up.
Comments
No comments yet. Start the discussion.