【问题标题】:Converting png to pdf with PIL save mode error使用 PIL 保存模式错误将 png 转换为 pdf
【发布时间】:2018-06-08 14:49:55
【问题描述】:

我正在尝试将 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:\Python\lib\site-packages\PIL\PdfImagePlugin.py", line 148, in _save
 raise ValueError("cannot save mode %s" % im.mode)
 ValueError: cannot save mode RGBA

【问题讨论】:

    标签: python-3.x python-imaging-library


    【解决方案1】:

    您需要先convert your PNG from RGBA to 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)
    

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 2012-02-28
      • 2011-09-15
      • 2016-08-21
      • 1970-01-01
      • 2013-12-27
      • 2011-02-21
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多