How to work with HEIC image file types in Python

后端 未结 6 1013
醉梦人生
醉梦人生 2021-01-31 18:08

The High Efficiency Image File (HEIF) format is the default when airdropping an image from an iPhone to a OSX device. I want to edit and modify these .HEIC files with Python.

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 18:34

    Simple solution after going over multiple responses from people.
    Please install whatimage, pyheif and PIL libraries before running this code.


    [NOTE] : I used this command for install.

    python3 -m pip install Pillow
    

    Also using linux was lot easier to install all these libraries. I recommend WSL for windows.


    • code
    import whatimage
    import pyheif
    from PIL import Image
    import os
    
    def decodeImage(bytesIo, index):
        with open(bytesIo, 'rb') as f:
        data = f.read()
        fmt = whatimage.identify_image(data)
        if fmt in ['heic', 'avif']:
        i = pyheif.read_heif(data)
        pi = Image.frombytes(mode=i.mode, size=i.size, data=i.data)
        pi.save("new" + str(index) + ".jpg", format="jpeg")
    
    # For my use I had my python file inside the same folder as the heic files
    source = "./"
    
    for index,file in enumerate(os.listdir(source)):
        decodeImage(file, index)
    

提交回复
热议问题