求助:Python中将JPG图片转换为HEIC格式的可行方案
Python实现JPG转HEIC的解决方案
问题原因
Pillow默认不支持HEIC格式的编解码,因此直接使用Image.save()保存为.heic会抛出unknown file extension: .heic错误。以下是两种可行的解决思路:
方案1:用pillow-heif扩展Pillow功能
pillow-heif是Pillow的第三方扩展,为其添加了HEIC格式的读写支持。
- 安装依赖:
pip install pillow-heif
- 示例代码:
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命令行工具完成转换。
安装libheif工具:
- Ubuntu/Debian:
sudo apt install libheif-examples - macOS:
brew install libheif - Windows:可从libheif官方仓库下载预编译二进制文件
- Ubuntu/Debian:
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
相关产品推荐
相关产品推荐

