close

How to work with HEIC image file types in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to work with HEIC image file types in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to work with HEIC image file types in Python?

  1. How to work with HEIC image file types in Python?

    Adding to the answer by danial, i just had to modify the byte array slighly to get a valid datastream for further work.

  2. work with HEIC image file types in Python

    Adding to the answer by danial, i just had to modify the byte array slighly to get a valid datastream for further work.

Method 1

You guys should check out this library, it’s a Python 3 wrapper to the libheif library, it should serve your purpose of file conversion, extracting metadata:

Example usage:

 import io

 import whatimage
 import pyheif
 from PIL import Image


 def decodeImage(bytesIo):

    fmt = whatimage.identify_image(bytesIo)
    if fmt in ['heic', 'avif']:
         i = pyheif.read_heif(bytesIo)

         # Extract metadata etc
         for metadata in i.metadata or []:
             if metadata['type']=='Exif':
                 # do whatever
        
         # Convert to other file format like jpeg
         s = io.BytesIO()
         pi = Image.frombytes(
                mode=i.mode, size=i.size, data=i.data)

         pi.save(s, format="jpeg")

  ...

Method 2

Adding to the answer by danial, i just had to modify the byte array slighly to get a valid datastream for further work. The first 6 bytes are ‘Exif\x00\x00’ .. dropping these will give you a raw format that you can pipe into any image processing tool.

import pyheif
import PIL
import exifread

def read_heic(path: str):
    with open(path, 'rb') as file:
        image = pyheif.read_heif(file)
        for metadata in image.metadata or []:
            if metadata['type'] == 'Exif':
                fstream = io.BytesIO(metadata['data'][6:])

    # now just convert to jpeg
    pi = PIL.Image.open(fstream)
    pi.save("file.jpg", "JPEG")

    # or do EXIF processing with exifread
    tags = exifread.process_file(fstream)

At least this worked for me.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read