gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:41:16 30 4
gpt4 key购买 nike

我正在尝试将条形码图像插入 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com