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

求助:Python中将JPG图片转换为HEIC格式的可行方案

Python实现JPG转HEIC的解决方案

问题原因

Pillow默认不支持HEIC格式的编解码,因此直接使用Image.save()保存为.heic会抛出unknown file extension: .heic错误。以下是两种可行的解决思路:


方案1:用pillow-heif扩展Pillow功能

pillow-heif是Pillow的第三方扩展,为其添加了HEIC格式的读写支持。

  1. 安装依赖:
pip install pillow-heif
  1. 示例代码:
from PIL import Image
import pillow_heif

# 注册HEIC格式编解码器
pillow_heif.register_heif_opener()

# 读取JPG图片
img = Image.open("input.jpg")
# 保存为HEIC格式,可通过quality参数调整画质(范围0-100)
img.save("output.heic", format="HEIC", quality=90)

方案2:调用libheif命令行工具

如果不想依赖Python扩展,可以直接调用系统中的libheif命令行工具完成转换。

  1. 安装libheif工具:

    • Ubuntu/Debian:sudo apt install libheif-examples
    • macOS:brew install libheif
    • Windows:可从libheif官方仓库下载预编译二进制文件
  2. Python中通过subprocess调用:

import subprocess

def convert_jpg_to_heic(input_path, output_path, quality=90):
    # 调用heif-enc命令执行转换
    subprocess.run(
        ["heif-enc", f"-q{quality}", input_path, "-o", output_path],
        check=True,
        capture_output=True
    )

# 调用示例
convert_jpg_to_heic("input.jpg", "output.heic")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:31:40