Heic to Jpg Image Converter

2024-06-11
By: O Wolfson

HEIC (High-Efficiency Image Coding) is a format commonly used by Apple devices for storing photos. While it's highly efficient in terms of storage, compatibility with non-Apple devices and software can be limited. Converting HEIC images to JPEG format ensures broader compatibility and ease of use. In this post, we'll walk you through a Node.js script that not only converts HEIC images to JPEG but also resizes and compresses them for optimal storage.

Prerequisites

Ensure you have Node.js and npm installed on your system. You can download and install them from nodejs.org.

Setting Up the Project

  1. Initialize a new Node.js project:

    bash
    mkdir heic_to_jpeg
    cd heic_to_jpeg
    npm init -y
    
  2. Install the necessary libraries:

    bash
    npm install heic-convert fs-extra sharp
    

The Script

Create a file named convert_heic_to_jpeg.js and add the following code:

javascript
const fs = require("fs");
const path = require("path");
const heicConvert = require("heic-convert");
const fsExtra = require("fs-extra");
const sharp = require("sharp");

const inputDirectory = "/Users/wolf/Desktop/Police_Report/_HEIC";
const outputDirectory = "/Users/wolf/Desktop/Police_Report/jpegs";

// Ensure the output directory exists
fsExtra.ensureDirSync(outputDirectory);

// Function to convert HEIC to JPEG and compress
async function convertHeicToJpeg(inputPath, outputPath) {
  try {
    const inputBuffer = fs.readFileSync(inputPath);
    const outputBuffer = await heicConvert({
      buffer: inputBuffer, // the HEIC file buffer
      format: "JPEG", // output format
      quality: 0.85, // the jpeg compression quality, between 0 and 1
    });

    // Resize and compress the image using sharp
    await sharp(outputBuffer)
      .resize({ width: 1920 }) // Adjust the width as needed, maintaining aspect ratio
      .jpeg({ quality: 70 }) // Adjust the quality as needed
      .toFile(outputPath);

    console.log(`Converted ${inputPath} to ${outputPath}`);
  } catch (error) {
    console.error(`Error converting ${inputPath}:`, error);
  }
}

// Process all HEIC files in the input directory
fs.readdir(inputDirectory, (err, files) => {
  if (err) {
    console.error("Error reading input directory:", err);
    return;
  }

  files.forEach((file) => {
    if (file.toLowerCase().endsWith(".heic")) {
      const inputPath = path.join(inputDirectory, file);
      const outputFilename = path.basename(file, path.extname(file)) + ".jpg";
      const outputPath = path.join(outputDirectory, outputFilename);
      convertHeicToJpeg(inputPath, outputPath);
    }
  });
});

Script Breakdown

  • Importing Required Modules:

    The script begins by importing necessary Node.js modules:

    • fs for file system operations.
    • path for handling file paths.
    • heic-convert for converting HEIC files to JPEG.
    • fs-extra for additional file system operations, like ensuring a directory exists.
    • sharp for image processing, including resizing and further compression.
  • Defining Directories:

    The inputDirectory variable specifies the location of the HEIC files, and the outputDirectory specifies where the converted JPEG files will be saved.

  • Ensuring Output Directory Exists:

    The fsExtra.ensureDirSync method creates the output directory if it doesn’t already exist.

  • Conversion Function:

    The convertHeicToJpeg function reads an HEIC file, converts it to JPEG, resizes it to a width of 1920 pixels while maintaining the aspect ratio, and compresses it with a quality setting of 70. This function uses heic-convert for the initial format conversion and sharp for resizing and further compression.

  • Processing Files:

    The fs.readdir method reads all files in the input directory. The script then filters for files with a .heic extension and processes each file using the convertHeicToJpeg function.

Running the Script

To run the script, navigate to your project directory in the terminal and execute:

bash
node convert_heic_to_jpeg.js

This script will convert all HEIC files in the specified input directory to JPEG format, resize them to a maximum width of 1920 pixels, and compress them to reduce file size.