如何使用Python 3脚本将HEIC格式转换为JPEG,然后转换为PDF?

yacmzcpb  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(135)

嗨,我正在尝试使用python3脚本将HEIC格式转换为jpg和jpg到pdf。我的休息代码是将jpg或png转换为pdf,适用于jpg和png。

# Python3 program to convert images to PDF
# including HEIC to JPEG conversion

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

try:
    # Storing image path
    img_path = "upload/" + sys.argv[1]
    
    # Check if the image is in HEIC format
    if img_path.lower().endswith('.heic'):
        # Convert HEIC to 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:
        # Opening image
        image = Image.open(img_path)

    # Storing PDF path
    pdf_path = "upload/" + sys.argv[1] + ".pdf"

    # Converting image to chunks using img2pdf
    pdf_bytes = img2pdf.convert(image.filename)

    # Opening or creating PDF file
    with open(pdf_path, "wb") as file:
        # Writing PDF files with chunks
        file.write(pdf_bytes)

    # Closing image file
    image.close()

    # Output
    print("true")
except Exception as e:
    # Output
    print("false")
    print(str(e))

字符串
我尝试了许多解决方案从Chatgpt但不工作。我希望它应该与其余代码工作,只是添加HEIC格式的JPG和JPG到PDF。

2guxujil

2guxujil1#

下面是一个例子:

from PIL import Image
from pathlib import Path
from pillow_heif import register_heif_opener
register_heif_opener()

files = list(Path(".").glob("*.heic")) + list(Path(".").glob("*.HEIC"))

for f in files:
    image = Image.open(str(f))
    image.convert('RGB').save(str(f.with_suffix('.jpg')))

字符串
有关CLI接口,请参见full python script

相关问题