【问题标题】:Unable to convert imgkit image to PIL image无法将 imgkit 图像转换为 PIL 图像
【发布时间】:2021-01-28 08:27:49
【问题描述】:

我正在尝试将 imgkit 图像转换为 PIL 图像以对其进行修改。当我尝试使用文件时,imgkit 成功地将 html 转换为图像。当我使用 BytesIO 并尝试转换为 PIL 图像时,出现错误。

这是我的代码:

img = imgkit.from_string(template.render(a=elements, r=range(len(elements))), False, config=config)
bytesImg = BytesIO(img)
bytesImg.seek(0)
image = Image.open(bytesImg) #error here

PIL.UnidentifiedImageError: 无法识别图像文件 <_io.bytesio object at>

我已经看过thisthis。 我是错误地将 imgkit 图像转换为字节还是有其他错误?

使用 Pillow 8.1 Python 3.9 和 imgkit 1.0.2

【问题讨论】:

  • 请问bytesImg的前20个字节是什么?
  • @MarkSetchell 。我使用了 print(bytesImg.read()) 并得到了 b'%PDF-1.4\n1 0 obj\n
  • 这看起来像是 PIL 只能写不能读的 PDF pillow.readthedocs.io/en/stable/handbook/… 你能强制 ImgKit 生成 JPEG 吗?
  • 是的,它奏效了。我弄乱了配置变量并将其转换为 pdf 而不是图像。

标签: python python-imaging-library imgkit


【解决方案1】:

是我错误地将 imgkit 图像转换为字节还是有其他错误?

我会从检查你的字节是否代表你的枕头理解的图像开始。内置模块 imghdr 如果您要排除它已知的格式之一就足够了(请参阅文档中的表格)。这种情况下的用法:

import imghdr

...

print(imghdr.what(None, h=img))

如果它确实识别格式,则检查您的 Pillow 是否支持它,否则您需要手动检查 file signature(几个起始字节)。

【讨论】:

  • 我尝试了 imghdr.what(None, h=img) 并得到了 'jpeg'。
  • 是的,你是对的。我的配置变量被弄乱了,并在我的主代码中转换为 pdf。它没有出现在测试中。谢谢
【解决方案2】:

imgkit 正在将 html 转换为 pdf,因为配置变量被搞砸了。

使用

which wkhtmltoimage

找到wkhtmltoimage的路径并设置

config = imgkit.config(wkhtmltoimage="path found")

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多