PyHEIF

0.8.0 · active · verified Thu Apr 16

PyHEIF is a Python 3.6+ interface to the `libheif` C library, enabling decoding of HEIF (High Efficiency Image Format) and HEIC images. It facilitates converting HEIF/HEIC images to raw pixel data, commonly used with libraries like Pillow. The current version is 0.8.0, with releases typically tied to Python version support and `libheif` updates, as well as new features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to decode a HEIF/HEIC image using `pyheif` and convert it into a Pillow `Image` object. It also shows how to handle both single-image and multi-image HEIF files introduced in `pyheif` 0.7.0. The decoded image is then saved as a PNG file. Remember to replace 'example.heic' with a path to a valid HEIC file.

import pyheif
from PIL import Image
import os

# This example assumes you have an 'example.heic' file.
# For a real scenario, replace 'example.heic' with your HEIF/HEIC file path.
# If you don't have one, you might need to create a dummy file or download one.
# For local testing without a file, this would fail, so ensure file exists.
# HEIF files often come from iPhones or other modern cameras.

try:
    # Read the HEIF file. This can return HeifFile or HeifContainer.
    heif_object = pyheif.read("example.heic")

    if isinstance(heif_object, pyheif.HeifContainer):
        # Handle multiple images (e.g., burst photos, depth maps)
        print(f"File contains {len(heif_object.heif_files)} images.")
        primary_image = heif_object.primary_image
    else:
        # Single image file
        primary_image = heif_object

    # Convert to Pillow Image
    # The 'raw' decoder requires mode and stride matching the heif_file output
    pillow_image = Image.frombytes(
        primary_image.mode,
        (primary_image.width, primary_image.height),
        primary_image.data,
        "raw",
        primary_image.mode,
        primary_image.stride,
    )

    # Save the image as PNG
    output_path = "output_image.png"
    pillow_image.save(output_path, "PNG")
    print(f"Successfully decoded and saved image to {output_path}")

except FileNotFoundError:
    print("Error: 'example.heic' not found. Please create or provide a valid HEIC file path.")
except pyheif.error.HeifError as e:
    print(f"Error decoding HEIF file: {e}")
except ImportError:
    print("Error: Pillow not installed. Please install with 'pip install Pillow'.")

view raw JSON →