← back to blog

Convert HEIC to JPG in Node.js on Linux (when sharp fails)

sharp can't read iPhone HEIC photos on Linux. We tested four ways to convert HEIC to JPG in Node.js, timed them, and show the one we run in production.

by Horizech Team6 min read

If you call sharp('photo.heic') on a Linux server with a real iPhone photo, you get this:

heif: Error while loading plugin: Support for this compression format has not been built in:
HEVC (a suitable decoder plugin is libde265) (11.6003)

We hit this while building the HEIC to JPG tool on Horizech Studio. This post shows why it happens, four ways around it, how fast each one is, and the code we run in production.

Short answer: install libheif-examples (plus libheif-plugin-libde265 on Ubuntu), decode with the heif-convert CLI, then hand the result to sharp. If you can't install system packages, use the heic-convert npm package. It needs no native code but runs about 1.75x slower.

Why sharp can't read HEIC

HEIC is a container (HEIF) holding an image compressed with HEVC, the H.265 video codec. sharp's prebuilt binaries ship libvips with libheif, but only with the AV1 decoder, so it reads .avif and not HEVC. You can check this yourself:

import sharp from 'sharp'
console.log(sharp.format.heif.input.fileSuffix) // [ '.avif' ]

Installing libde265 on the system does not help, because sharp uses its own bundled libvips, not the system one. We confirmed that: sharp still failed after we installed the decoder plugin system-wide.

The four options we tested

MethodNeeds system packagesWorks on HEVC HEICNotes
sharp (0.35.6, prebuilt)NoNoFails with the error above
heic-convert npm (libheif as WebAssembly)NoYesPure JS install, slowest
heif-convert CLI (libheif 1.17.6)YesYesFastest
ImageMagick 6 convertYesYesUses the same system libheif

Benchmark results

We converted four HEIC files to JPEG at quality 90 and took the median of 5 runs. The test machine was a 4 vCPU Linux container on Ubuntu 24.04 with Node 22.

The test files were freely licensed sample photos from the scikit-image sample data, encoded to HEIC with x265 at quality 80. The 12 MP file is the retina photo upscaled to 4032x3024, the resolution of a standard iPhone photo, so the timings match what a real upload costs.

FileSizeheic-convert (wasm)heif-convert (CLI)ImageMagick
astronaut, 512x512118 KB84 ms44 ms50 ms
hubble, 1000x872519 KB210 ms124 ms135 ms
retina, 1411x1411375 KB267 ms155 ms188 ms
retina, 4032x3024 (12 MP)1,775 KB1,539 ms878 ms1,022 ms

What this tells you:

  • The CLI is the fastest every time, about 1.75x quicker than the WebAssembly build on a 12 MP photo.
  • ImageMagick is close, because it calls the same libheif. Use it if it's already in your image. There's no reason to add it just for HEIC.
  • WebAssembly is fine for low volume. About 1.5 seconds per 12 MP photo is acceptable for an occasional upload. On a 1 vCPU server handling many uploads, it adds up quickly.
  • Output sizes differ by up to 25% at the same "quality 90", because each tool maps quality to its JPEG encoder differently. Don't compare tools on file size unless you also compare quality.

The full script and raw output are in the example folder on GitHub. Run it on your own photos with node bench.mjs path/to/heic-folder.

Installing the decoder (the Ubuntu gotcha)

On Debian bookworm (the base of the official node Docker images), one package is enough, because libheif1 there links libde265 directly:

RUN apt-get update && apt-get install -y --no-install-recommends libheif-examples \
  && rm -rf /var/lib/apt/lists/*

On Ubuntu 24.04 that's not enough. libheif 1.17 there loads decoders as plugins, and libheif-examples doesn't pull in the HEVC one. You get a working heif-convert that fails on every iPhone photo:

$ heif-convert -q 90 photo.heic out.jpg
Could not decode image: 0: Unsupported feature: Unsupported codec

Install the plugin as well:

sudo apt-get install -y libheif-examples libheif-plugin-libde265

After that, the same command prints Written to out.jpg.

The production code

This is the helper we use. It decodes with the CLI and lets sharp do everything else (resize, re-encode), so you keep sharp's speed for the rest of your pipeline. If the CLI isn't installed, for example on a developer laptop, it falls back to the WebAssembly decoder.

import { execFile } from 'node:child_process'
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import sharp from 'sharp'

const HEIF_CONVERT = process.env.HEIF_CONVERT_PATH ?? 'heif-convert'

async function decodeWithCli(file) {
  const dir = await mkdtemp(path.join(tmpdir(), 'heic-'))
  try {
    await new Promise((resolve, reject) =>
      // execFile, not exec: the file name never passes through a shell.
      execFile(HEIF_CONVERT, [file, path.join(dir, 'out.png')], { timeout: 60_000 },
        err => (err ? reject(err) : resolve())))
    // Burst or multi-image files write out-1.png, out-2.png...; the first is the primary photo.
    const pngs = (await readdir(dir)).filter(f => f.endsWith('.png')).sort()
    if (!pngs.length) throw new Error('heif-convert produced no output')
    return await readFile(path.join(dir, pngs[0]))
  } finally {
    await rm(dir, { recursive: true, force: true })
  }
}

async function decodeWithWasm(file) {
  const { default: heicConvert } = await import('heic-convert')
  return Buffer.from(await heicConvert({ buffer: await readFile(file), format: 'PNG' }))
}

export async function heicToJpeg(file, { quality = 85, maxWidth } = {}) {
  let png
  try {
    png = await decodeWithCli(file)
  } catch (e) {
    if (e.code !== 'ENOENT') throw e // CLI exists but failed: a real error, don't hide it
    png = await decodeWithWasm(file)
  }
  let img = sharp(png)
  if (maxWidth) img = img.resize({ width: maxWidth, withoutEnlargement: true })
  return img.jpeg({ quality, mozjpeg: true }).toBuffer()
}

We tested both paths: with the CLI, a 12 MP HEIC became a 2048x1536 JPEG of 158 KB. With HEIF_CONVERT_PATH pointed at a missing binary, the WebAssembly fallback took over and produced the same output.

Three details that matter in production:

  1. Decode to PNG, not JPEG. PNG is lossless, so the photo is compressed only once, at the end, by sharp with the settings you chose.
  2. Use execFile with a timeout. It keeps user-supplied file names away from a shell, and it stops a malformed file from tying up a CPU forever.
  3. Only fall back on ENOENT. If the CLI is installed but fails, the file is probably corrupt. Falling back would just fail more slowly and hide the real error.

Which one should you use?

  • You control the server or Docker image: heif-convert CLI + sharp, as above.
  • Serverless or no root access: heic-convert alone. It's slower but needs nothing installed.
  • You only convert a few photos by hand: you don't need code. Our free HEIC to JPG converter runs this exact pipeline.
// no code needed?
Do it online with Horizech Studio HEIC to JPG. Free, no sign-up.
open the tool ↗
⚡
Written by Horizech Team

Part of the team at Horizech — we build Flutter apps, AI integrations, web platforms, and games. If you want this done for you, get in touch.

hire us →
← all posts