How to Convert From HEIC to JPG in Python on WIndows
Asked Answered
B

8

13

Im trying to convert HEIC to JPG using python. The only other answers about this topic used pyheif. I am on windows and pyheif doesn't support windows. Any suggestions? I am currently trying to use pillow.

Bilicki answered 13/9, 2020 at 0:52 Comment(2)
I have the same issue. Did you come up with a solution?Cyrstalcyrus
Try lfd.uci.edu/~gohlke/pythonlibs/#pyheifZirkle
U
24

The following code will convert an HEIC file format to a PNG file format

from PIL import Image
import pillow_heif

heif_file = pillow_heif.read_heif("HEIC_file.HEIC")
image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",
)

image.save("./picture_name.png", format("png"))
Urn answered 2/3, 2022 at 19:56 Comment(2)
This works and should be the answer.Braw
TypeError: argument 1 must be read-only bytes-like object, not memoryview. I changed heif_file.data to heif_file.data.tobytes() and it worked.Aaronson
S
3

As of today, I haven't found a way to do this with a Python-only solution. If you need a workaround, you can find any Windows command line utility that will do the conversion for you, and call that as a subprocess from Python.

Here is an example option using PowerShell: https://github.com/DavidAnson/ConvertTo-Jpeg

It's also pretty easy these days to write a .NET-based console app that uses Magick.NET. That's what I ended up doing.

Sillabub answered 27/12, 2020 at 21:48 Comment(0)
L
2

Work for me.

from PIL import Image
import pillow_heif


pillow_heif.register_heif_opener()

img = Image.open('c:\image.HEIC')
img.save('c:\image_name.png', format('png'))
Lunitidal answered 31/1, 2023 at 11:52 Comment(0)
E
1

Just was looking at the same topic. I came across this:

https://pypi.org/project/heic-to-jpg/

I haven't had time to look more into this, but thought I'd share this.

Eal answered 15/10, 2021 at 20:23 Comment(3)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewMaestoso
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Stallings
heic-to-jpg readme has this warning for Windows 👉 ⚠️ Please note that this has been tested on macOS only. There might be issues on other operating systemsAlodi
F
1

Please, use open_heif or PIL.Image.open() if you need some Pillow things to do with image.

pillow-heif supports lazy loading of data.

read_heif and read are slow for files containing multiply images, it will decode all of them during call.

P.S.: I am the author of pillow-heif.

Frenulum answered 9/6, 2022 at 20:24 Comment(2)
Hi, Alexander, thanks for adding heif support to pillow, I'm facing weird behaviour with pillow-heif, when I try to resize JPG files it takes just milliseconds to load them, but when I try to open HEIC photo using your plugin it takes around 1 second to load the picture on intel processor in EC2, is there something I can do to increase HEIC loading speed?Solvency
such questions are for github, create an issue there with an example and we will see what can be done.Frenulum
A
1

I use this code to convert an image from a form from heic to jpeg a before I save it to a local file system.

This code does some renaming, so it can be saved as FileStorage object in the db with access to filename and mime type.

As function of the Class Converter.

import io
from PIL import Image
import pillow_heif
from werkzeug.datastructures import FileStorage

class Converter:

    def convert_heic_to_jpeg(self, file):
        # Check if file is a .heic or .heif file
        if file.filename.endswith(('.heic', '.heif', '.HEIC', '.HEIF')):
            # Open image using PIL
            # image = Image.open(file)

            heif_file = pillow_heif.read_heif(file)
            image = Image.frombytes(
                heif_file.mode,
                heif_file.size,
                heif_file.data,
                "raw",
            )

            # Convert to JPEG
            jpeg_image = image.convert('RGB')

            # Save JPEG image to memory temp_img
            temp_img = io.BytesIO()
            jpeg_image.save(temp_img, format("jpeg"))

            # Reset file pointer to beginning of temp_img
            temp_img.seek(0)

            # Create a FileStorage object
            file_storage = FileStorage(temp_img, filename=f"{file.filename.split('.')[0]}.jpg")

            # Set the mimetype to "image/jpeg"
            file_storage.headers['Content-Type'] = 'image/jpeg'

            return file_storage
        else:
            raise ValueError("File must be of type .heic or .heif")
Ardine answered 9/1, 2023 at 14:57 Comment(1)
But use open_heif as Mr. Alexander Piskun said. The speed is much higher. --- speed test -- open_heif: | 0.0064 sec --- --- speed test -- read_heif: | 0.1881 sec ---Molluscoid
U
0

In the latest version of pillow_heic module, below code will work fine. only read_heif is replaced with read.

from PIL import Image

import pillow_heif

heif_file = pillow_heif.read(r"E:\image\20210914_150826.heic")

image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",

)

image.save(r"E:\image\test.png", format("png"))
Untaught answered 20/5, 2022 at 7:16 Comment(0)
G
0

Here is an easy implementation to convert a folder of files from HEIC to JPG

    import os
    from PIL import Image
    import pillow_heif
    
    
    def convert_heic_to_jpeg(heic_path, jpeg_path):
        img = Image.open(heic_path)
        img.save(jpeg_path, format='JPEG')
    
    
    def convert_all_heic_to_jpeg(input_folder, output_folder):
        # Register HEIF opener with Pillow
        pillow_heif.register_heif_opener()
    
        # Create output folder if it doesn't exist
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
    
        # List all files in input folder
        for filename in os.listdir(input_folder):
            # Check if file is a HEIC file
            if filename.endswith(".heic") or filename.endswith(".HEIC"):
                # Build full path to input and output file
                heic_path = os.path.join(input_folder, filename)
                jpeg_filename = f'{os.path.splitext(filename)[0]}.jpg'
                jpeg_path = os.path.join(output_folder, jpeg_filename)
    
                # Convert HEIC to JPEG
                convert_heic_to_jpeg(heic_path, jpeg_path)
    
    
    # Example usage
    input_folder = 'images'
    output_folder = 'converted'
    convert_all_heic_to_jpeg(input_folder, output_folder)
Grandniece answered 2/10, 2023 at 12:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.