DEV Community

Sanjaya  Ranasinghe
Sanjaya Ranasinghe

Posted on

How to Convert HEIC to JPG Programmatically Using Node.js

If you build web applications that allow users to upload profile pictures or gallery items, you have likely run into the HEIC format.

By default, Apple devices capture photos in HEIC to save storage space. However, many web browsers and older systems still struggle to render HEIC images smoothly.

In this guide, let's look at how you can programmatically convert HEIC images to standard JPG format using Node.js.


Prerequisites

To handle image conversion efficiently in Node.js, we will use the popular sharp library.

Run the following command to install the required packages:

npm install sharp express multer
Enter fullscreen mode Exit fullscreen mode

The Conversion Script
Here is a clean Node.js function using sharp to convert an uploaded HEIC image buffer into a compressed JPG file:

const sharp = require('sharp');

async function convertHeicToJpg(inputBuffer) {
  try {
    const outputBuffer = await sharp(inputBuffer)
      .jpeg({ quality: 85 })
      .toBuffer();

    return outputBuffer;
  } catch (error) {
    console.error('Error converting image:', error);
    throw error;
  }
}

module.exports = { convertHeicToJpg };
Enter fullscreen mode Exit fullscreen mode

Integrating with Express

If you are handling file uploads via Express and multer, you can automatically convert any incoming HEIC file:

const express = require('express');
const multer = require('multer');
const { convertHeicToJpg } = require('./converter');

const upload = multer({ storage: multer.memoryStorage() });
const app = express();

app.post('/upload', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).send('No file uploaded.');
    }

    let imageBuffer = req.file.buffer;
    let mimeType = req.file.mimetype;

    if (mimeType === 'image/heic' || mimeType === 'image/heif' || req.file.originalname.match(/\.heic$/i)) {
      imageBuffer = await convertHeicToJpg(imageBuffer);
      console.log('Successfully converted HEIC to JPG!');
    }

    res.status(200).send('Image processed successfully.');
  } catch (err) {
    res.status(500).send('Server error during image processing.');
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Conclusion
Handling HEIC uploads gracefully ensures a seamless user experience for iPhone users. If you are looking for a ready-made web tool that handles batch conversions instantly, use our free online converter at HEIC to JPG Converter.

How do you usually handle image optimization in your web applications? Let me know in the comments below! 👇

Top comments (0)