pythonheic

Different filesize when changing heic to jpeg in python


I could easily convert HEIC to JPEG in python with a pyheic library. But the filesize gets larger when it's converted to JPEG. (About 4 times). Can I reduce the size of the file saving it?

How can I get base64-encoded string instead of saving JPEG image?

My code is as follows:

# -*- coding: utf-8 -*-
import sys 
import os
from PIL import Image # pip3 install pillow
import pyheif  # pip3 install pyheif 


def call(oriPath, defPath):
    try:
        # if defPath is webp or heic
        fileType = oriPath.split(".")[-1]
        if fileType == "heic":
            heif_file = pyheif.read(oriPath)
            image = Image.frombytes(
                heif_file.mode,
                heif_file.size,
                heif_file.data,
                "raw",
                heif_file.mode,
                heif_file.stride,
            )

        image.save(defPath, "JPEG")

    except:
        print(False)
        return

    print(True)

Solution

  • Since you are converting from one data type to the other the format is changing. I am not too familiar with HEIC but it could be the case that it is simply a smaller file size with the compression parameters that you have set for the JPEG.

    wikipedia has the following to say about it

    A HEIF image using HEVC requires less storage space than the equivalent quality JPEG.

    So unless you want to drop the quality it might not even be possible to get a smaller image (note: I have no idea what type the HEIC/HEIF is).

    As for the base64 encoded string, you could just read the binary data and convert it to base64 per this question: Python: How do I convert from binary to base 64 and back?