将 png 转换为带有 PIL 保存模式错误的 pdf



我试图将png文件转换为pdf文件。PIL似乎是这样做的方法,但是我在运行时遇到错误(cannot save mode RGBA

法典:

import os
import PIL
from PIL import Image
path = 'E:path_to_file'
filename = '15868799_1.png'
fullpath_filename = os.path.join(path, filename)
im = PIL.Image.open(fullpath_filename)
newfilename = '15868799.pdf'
newfilename_fullpath = os.path.join(path, newfilename)
PIL.Image.Image.save(im, newfilename_fullpath, "PDF", resoultion=100.0)

错误:

File "C:Pythonlibsite-packagesPILPdfImagePlugin.py", line 148, in _save
raise ValueError("cannot save mode %s" % im.mode)
ValueError: cannot save mode RGBA

您需要先将PNG从RGBA转换为RGB。

示例代码:

from PIL import Image
PNG_FILE = 'E:path_to_file15868799_1.png'
PDF_FILE = 'E:path_to_file15868799.pdf'
rgba = Image.open(PNG_FILE)
rgb = Image.new('RGB', rgba.size, (255, 255, 255))  # white background
rgb.paste(rgba, mask=rgba.split()[3])               # paste using alpha channel as mask
rgb.save(PDF_FILE, 'PDF', resoultion=100.0)

为了转换多个RGBApng 图像,我选择了这个代码段,

from PIL import Image
_source = "/mnt/ssd/presentations"
_files = [] # List of image path populated using glob
def conv_rgba_to_rgb(_rgba):
_rgba = Image.open(_rgba)
_rgb = Image.new('RGB', _rgba.size, (255, 255, 255))
_alpha = _rgba.split()[-1]
_rgb.paste(_rgba, mask=_rgba.putalpha(_alpha))
return _rgb
_images = [conv_rgba_to_rgb(_f) for _f in _files]
_pdf_path = f"{_source}/phd-presentation.pdf"
_images[0].save(_pdf_path, "PDF", resolution=72.0, save_all=True, append_images=_images[1:])

最新更新