使用 PIL 保存模式错误将 png 转换为 pdf [英] Converting png to pdf with PIL save mode error

查看:279
本文介绍了使用 PIL 保存模式错误将 png 转换为 pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to convert png files into pdf's. PIL seems to be the way to do it but Im getting an error (cannot save mode RGBA) when running it

代码:

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:\Python\lib\site-packages\PIL\PdfImagePlugin.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_file\15868799_1.png'
PDF_FILE = 'E:\path_to_file\15868799.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)

这篇关于使用 PIL 保存模式错误将 png 转换为 pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆