Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HEIC to JPEG conversion with metadata

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")
like image 915
Trics Avatar asked Apr 25 '26 04:04

Trics


2 Answers

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)
like image 193
Trics Avatar answered Apr 27 '26 17:04

Trics


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)
like image 21
f41_ardu Avatar answered Apr 27 '26 18:04

f41_ardu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!