Tad*_*eck 5 python django reportlab temporary-files stringio
我正在尝试解码 base64 编码的图像并将其放入我使用 ReportLab 生成的 PDF 中。我目前是这样做的(image_data是 base64 编码的图像,story已经是 ReportLab 的故事):
# There is some "story" I append every element
img_height = 1.5 * inch # max image height
img_file = tempfile.NamedTemporaryFile(mode='wb', suffix='.png')
img_file.seek(0)
img_file.write(image_data.decode('base64'))
img_file.seek(0)
img_size = ImageReader(img_file.name).getSize()
img_ratio = img_size[0] / float(img_size[1])
img = Image(img_file.name,
width=img_ratio * img_height,
height=img_height,
)
story.append(img)
Run Code Online (Sandbox Code Playgroud)
它有效(尽管对我来说仍然很难看)。我想摆脱临时文件(文件类对象不应该起作用吗?)。
为了摆脱临时文件,我尝试使用StringIO模块,创建类文件对象并传递它而不是文件名:
# There is some "story" I append every element
img_height = 1.5 * inch # max image height
img_file = StringIO.StringIO()
img_file.seek(0)
img_file.write(image_data.decode('base64'))
img_file.seek(0)
img_size = ImageReader(img_file).getSize()
img_ratio = img_size[0] / float(img_size[1])
img = Image(img_file,
width=img_ratio * img_height,
height=img_height,
)
story.append(img)
Run Code Online (Sandbox Code Playgroud)
但这给了我IOError和以下消息:“无法识别图像文件”。
我知道 ReportLab 使用 PIL 来读取与 jpg 不同的图像,但是有什么方法可以避免创建命名的临时文件并且仅使用类文件对象执行此操作,而无需将文件写入磁盘?
我对 ReportLab 不熟悉,但如果你可以直接使用 PIL,这将起作用:
...
img = Image.open(img_file)
width, height = img.size
...
Run Code Online (Sandbox Code Playgroud)
你可以在这里查看 PIL Image 类参考
| 归档时间: |
|
| 查看次数: |
2984 次 |
| 最近记录: |