python - 从 PIL 图像或 StringIO 将图像插入 Reportlab

标签 python python-imaging-library reportlab

我正在尝试将条形码图像插入 Reportlab。我知道对此有很多问题,但所有问题都假设您已经在目录或文件系统中拥有图像文件。

由于 Reportlab 在 EAN13 条形码方面存在问题,我决定使用另一个名为 pyBarcode 的包为我生成图像。

最初我将图像保存在 StringIO 实例中并将其直接传递给 reportlab.platypus.flowables.Image 但这似乎不起作用。然后我阅读了文档:

Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library) are supported.

这是否意味着如果我传递一个 PIL 图像,这应该可以工作?当我尝试以下操作时出现异常:

>>> import PIL
>>> from reportlab.platypus.flowables import Image
>>> fp = StringIO(the_barcode.getvalue())
>>> barcode_image = PIL.Image.open(fp)
>>> doc = SimpleDocTemplate('barcode.pdf')
>>> story = [Image(barcode_image)]
>>> Traceback (most recent call last):
  File "create.py", line 57, in <module>
    main()
  File "create.py", line 24, in main
    save_pdf(fp, STYLE, ART, COLOR, SIZE)
  File "create.py", line 28, in save_pdf
    fp = StringIO(fp.getvalue())
  File "/home/mark/.virtualenvs/barcode/local/lib/python2.7/site-packages/reportlab-2.6-py2.7-linux-i686.egg/reportlab/platypus/flowables.py", line 402, in __init__
    if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
  File "/home/mark/.virtualenvs/barcode/lib/python2.7/posixpath.py", line 95, in splitext
    return genericpath._splitext(p, sep, altsep, extsep)
  File "/home/mark/.virtualenvs/barcode/lib/python2.7/genericpath.py", line 91, in _splitext
    sepIndex = p.rfind(sep)
  File "/home/mark/.virtualenvs/barcode/local/lib/python2.7/site-packages/PIL/Image.py", line 512, in __getattr__
    raise AttributeError(name)
AttributeError: rfind

不知何故,PIL Image 似乎也不起作用。如果我没有图像的文件名(因为我的图像是在内存中创建的),我应该将什么作为第一个参数传递给 Reportlab 的 Image 函数?

最佳答案

我对建议的方法没有运气。

检查 pdfdoc.py 中的代码显示,AttributError 是由于将 StringIO 视为文件名:

    if source is None:
        pass # use the canned one.
    elif hasattr(source,'jpeg_fh'):
        self.loadImageFromSRC(source)   #it is already a PIL Image
    else:
        # it is a filename

进一步查看源码,发现jpeg_fh是reportlab.lib.utils中ImageReader类的一个属性。 ImageReader 接受 StringIO 和 PIL 图像。

所以将 StringIO 包装在 ImageReader 中解决了我的问题:

import PIL
from reportlab.lib.utils import ImageReader

io_img = StringIO(data)
pil_img = PIL.Image.open(StringIO(data))

reportlab_io_img = ImageReader(io_img)
reportlab_pil_img = ImageReader(pil_img)

canvas.drawImage(reportlab_io_img, ...)
canvas.drawImage(reportlab_pil_img, ...)

关于python - 从 PIL 图像或 StringIO 将图像插入 Reportlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953659/

相关文章:

.net - 从 Python 到 F# 的字符串替换实用程序转换

python - django View 中的简单 for 循环创建 pdf 文件

python - Pandas 在groupby中表示跨行和列

python - Heroku 在 Virtual Env 上安装 PIL 依赖时出错

python - 如何提高这种numpy迭代的效率?

python - (Python) 使用 PIL 或 PyPNG 在图像中设置特定调色板

python - 如何使用Report Lab 的 Canvas drawImage() 插入图像?

python - 如何使用Reportlab编写选项卡?

python - 如何使用 pyodbc 加速批量插入 MS SQL Server

Python 装饰器访问自身