Opening .HEIC images with Python

Svensson
1 min readJan 18, 2021

The most common python library for image modification is Pillow (PIL). It can handle almost all image formats, except for a few, among which High Efficiency Image File Format (HEIC), is one of them. This is a rather common problem as it became the standard iPhone image format in iOS 11 released in 2017.

It has been requested many times to be added in the Pillow library but as of February 2021, Pillow still does not support the format. (See request and discussion here: https://github.com/python-pillow/Pillow/issues/2806 )

Luckily there is a library that does exactly what we need to easy integrate it with your normal Pillow workflow. The library is called pyheif and can be installed using pip from the terminal. https://pypi.org/project/pyheif/

pip install pyheif 

Below is an example of a function that can handle opening images of “normal” Pillow formats as well as .heic.

from PIL import Pillow
import pyheif
def work_with_image(file_path) # Check if image format is .heic
if self.original_filename.split('.')[-1] == 'heic':
heif_file = pyheif.read(pdf_src_path)
image = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride)
else: # assume "normal" image that pillow can open
image = Image.open(file_path)
# Continue your workflow below

There are also ways to pass an IoByte object instead of a file path. You can read more about that in the documentation linked above.

Hope this was helpful!

/Svensson

--

--

Svensson

Technical Product Manager based in Silicon Valley. Former Software Engineer. Stanford Engineering 2020.