Converting HEIF to JPEG in Python

Introduction

High Efficiency Image Format (HEIF) is a container format for individual images and image sequences. HEIF files are efficient but not as widely supported as JPEG or PNG. Fortunately, Python offers straightforward ways to convert HEIF to more commonly supported formats.

Prerequisites

To proceed, you'll need Python installed on your system, along with the Python package manager (pip). You will also need the pyheif and PIL (Pillow) libraries.

Installation

    
    pip install pyheif
    pip install Pillow
    
  

Code Example

    
    import pyheif
    from PIL import Image

    def heif_to_jpeg(heif_path, jpeg_path):
      # Read HEIF file
      heif_file = pyheif.read(heif_path)

      # Convert to PIL Image
      image = Image.frombytes(
        heif_file.mode,
        heif_file.size,
        heif_file.data,
        "raw",
        heif_file.mode,
        heif_file.stride,
      )

      # Save as JPEG
      image.save(jpeg_path, format="JPEG")
    
  

Usage

    
    heif_path = "example.heic"
    jpeg_path = "example.jpg"
    heif_to_jpeg(heif_path, jpeg_path)
    
  

Conclusion

Converting HEIF to JPEG is simple with Python. By using the pyheif and PIL libraries, you can seamlessly integrate this conversion into your workflow.