Convert and resize iPhone images with Python

Photos taken with an iPhone results in files with the .heic extension.

The PIL Python library helps with file conversion & more Python library: Pillow

from PIL import Image, ImageOps
import pillow_heif

input_folder = '/path/to/folder/with/heic/'
output_folder = '/path/to/output/jpeg/'

existing_files = [f"{input_folder}/{file}" for file in os.listdir(input_folder) if '.heic' in file.lower()]

for file in existing_files:
    count += 1
    heif_file = pillow_heif.read_heif(file)
    image = Image.frombytes(
        heif_file.mode,
        heif_file.size,
        heif_file.data,
        "raw",
    )

    image = ImageOps.contain(image, (1000,1000))
    image.save(f"{output_folder}/{date}_{count}.jpg", optimize=True) # can add quality=80

The ImageOps.contain is great: it enables to resize an image ensuring ouput image does not go beyond the limits of the "box" (1000 x 1000 here) while keeping original ratio.

links

social