You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用pyheif转HEIC为JPEG时文件变大及获取base64编码问题

解决方案

1. 减小JPEG输出体积

Pillow的Image.save()方法保存JPEG格式时,默认画质参数为95(最高为100),是导致输出体积偏大的核心原因,你可以通过以下三个参数自定义压缩规则:

  • quality:取值范围1-100,数值越低压缩率越高、体积越小,通常设置为60~80区间即可兼顾画质和体积,肉眼几乎看不出差异
  • optimize:设为True时会额外对图片Huffman表进行优化,在相同画质下进一步减小体积
  • subsampling:色度抽样参数,设为1对应4:2:0抽样(大部分数码照片的默认抽样标准),可降低冗余色度信息减小体积

修改后的保存代码示例:

image.save(defPath, "JPEG", quality=70, optimize=True, subsampling=1)

2. 不保存本地直接获取base64编码

使用io.BytesIO内存文件对象承接保存的JPEG数据,无需写入本地磁盘,直接读取内存数据后编码为base64即可,修改后的完整代码如下:

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

# 转换后直接返回base64的函数示例
def heic_to_jpeg_base64(oriPath, quality=70):
    try:
        fileType = oriPath.split(".")[-1].lower()
        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,
            )
        else:
            # 兼容其他格式图片输入
            image = Image.open(oriPath)
        
        # 写入内存对象
        img_buffer = BytesIO()
        image.save(img_buffer, "JPEG", quality=quality, optimize=True, subsampling=1)
        # 读取字节数据转base64
        base64_str = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
        # 可选:添加base64图片头,方便前端直接使用
        # base64_str = f"data:image/jpeg;base64,{base64_str}"
        return base64_str
    except Exception as e:
        print(f"转换失败:{e}")
        return None

# 原保存到本地的函数也可以同步修改参数减小体积
def call(oriPath, defPath):
    try:
        fileType = oriPath.split(".")[-1].lower()
        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,
            )
        else:
            image = Image.open(oriPath)

        image.save(defPath, "JPEG", quality=70, optimize=True, subsampling=1)

    except:
        print(False)
        return

    print(True)

内容的提问来源于stack exchange,提问作者user1942626

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:15:04