HEIC to JPEG conversion with metadata

5.9k views Asked by At

I'm trying to convert heic file in jpeg importing also all metadata (like gps info and other stuff), unfurtunately with the code below the conversion is ok but no metadata are stored on the jpeg file created. Anyone can describe me what I need to add in the conversion method?

heif_file = pyheif.read("/transito/126APPLE_IMG_6272.HEIC")
image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",
    heif_file.mode,
    heif_file.stride,
)
image.save("/transito/126APPLE_IMG_6272.JPEG", "JPEG")
3

There are 3 answers

3
Trics On

Thanks, i found a solution, I hope can help others:

# Open the file
heif_file = pyheif.read(file_path_heic)

# Creation of image 
image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",
    heif_file.mode,
    heif_file.stride,
)
# Retrive the metadata
for metadata in heif_file.metadata or []:
    if metadata['type'] == 'Exif':
        exif_dict = piexif.load(metadata['data'])

# PIL rotates the image according to exif info, so it's necessary to remove the orientation tag otherwise the image will be rotated again (1° time from PIL, 2° from viewer).
exif_dict['0th'][274] = 0
exif_bytes = piexif.dump(exif_dict)
image.save(file_path_jpeg, "JPEG", exif=exif_bytes)
0
Alexander Piskun On

HEIF to JPEG:

from PIL import Image
import pillow_heif

if __name__ == "__main__":
    pillow_heif.register_heif_opener()
    img = Image.open("any_image.heic")
    img.save("output.jpeg")

JPEG to HEIF:

from PIL import Image
import pillow_heif

if __name__ == "__main__":
    pillow_heif.register_heif_opener()
    img = Image.open("any_image.jpg")
    img.save("output.heic")
  1. Rotation (EXIF of XMP) will be removed automatically when needed.

  2. Call to register_heif_opener can be replaced by importing pillow_heif.HeifImagePlugin instead of pillow_heif

  3. Metadata can be edited in Pillow's "info" dictionary and will be saved when saving to HEIF.

0
f41_ardu On

Here is an other approach to convert iPhone HEIC images to JPG preserving exif data

  1. Pyhton 3.9 (I'm on Rasperry PI 4 64 bit)
  2. install pillow_heif (0.8.0)

And run following code and you'll find exif data in the new JPEG image. The trick is to get the dictionary information. No additional conversion required.

This is sample code, built your own wrapper around.

    from PIL import Image
    import pillow_heif

    # open the image file
    heif_file = pillow_heif.read_heif("/mnt/pictures/test/IMG_0001.HEIC")
   
    #create the new image
    image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",
    heif_file.mode,
    heif_file.stride,
    )

    print(heif_file.info.keys())
    dictionary=heif_file.info
    exif_dict=dictionary['exif']
    # debug 
    print(exif_dict)
    
    image.save('/tmp/test000.JPG', "JPEG", exif=exif_dict)