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

如何用Python3脚本实现HEIC转JPEG再转PDF?

实现HEIC转JPEG再转PDF的Python脚本

我已有一套可将JPG/PNG转换为PDF的后端代码,现在需要新增HEIC格式图片转JPEG后再转PDF的功能。试过ChatGPT提供的多种方案都无效,于是基于原有可用代码编写了如下实现:

# Python3 图片转PDF程序
# 包含HEIC转JPEG功能

import img2pdf
from PIL import Image
import os
import sys
import pyheif

try:
    # 存储图片路径
    img_path = "upload/" + sys.argv[1]
    
    # 检查图片是否为HEIC格式
    if img_path.lower().endswith('.heic'):
        # 将HEIC转换为JPEG
        heif_file = pyheif.read(img_path)
        img_path = img_path.rsplit('.', 1)[0] + '.jpg'
        image = Image.frombytes(
            heif_file.mode, 
            heif_file.size, 
            heif_file.data,
            "raw",
            heif_file.mode,
            heif_file.stride,
        )
        image.save(img_path, format='JPEG')
    else:
        # 打开非HEIC格式图片
        image = Image.open(img_path)

    # 存储PDF路径
    pdf_path = "upload/" + sys.argv[1] + ".pdf"

    # 使用img2pdf将图片转换为PDF字节流
    pdf_bytes = img2pdf.convert(image.filename)

    # 打开或创建PDF文件并写入内容
    with open(pdf_path, "wb") as file:
        file.write(pdf_bytes)

    # 关闭图片文件
    image.close()

    # 输出转换成功标识
    print("true")
except Exception as e:
    # 输出转换失败标识及错误信息
    print("false")
    print(str(e))

代码核心说明

  • 依赖准备:需提前安装img2pdf、Pillow、pyheif库,执行命令pip install img2pdf pillow pyheif即可完成安装
  • HEIC转换逻辑:通过pyheif读取HEIC文件的原始数据,再用Pillow将数据转为JPEG格式并本地保存
  • 兼容原有功能:保留了原有的JPG/PNG转PDF流程,仅针对HEIC格式新增判断与转换分支
  • 错误排查:通过全局异常捕获,输出明确的成功/失败标识及错误详情,便于定位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 09:12:51