【问题标题】:Create a file object from raw binary information in Python从 Python 中的原始二进制信息创建文件对象
【发布时间】:2015-03-10 03:25:35
【问题描述】:

问题

在 Python 中从原始二进制信息创建文件对象的干净方法是什么?

更多信息

我需要这样做的原因是因为我有包含存储在 ram 中的 jpeg 图像的原始二进制信息。我需要将它放在某种文件对象中,以便我可以使用 Python 的 Pillow 库调整图像大小。

根据pillow documentation,文件对象需要实现read()seek()tell()方法。

文件对象必须实现 read()、seek() 和 tell() 方法,并以二进制模式打开。

【问题讨论】:

标签: python file-io python-imaging-library pillow


【解决方案1】:

我能够在PIL.Image.frombytes 的文档中找到有关如何处理这种情况的提及:

...如果您在字符串中有整个图像,请将其包装在 BytesIO 对象中, 并使用 open() 加载它。

这就是我使用BytesIO 得到的结果:

import io
import PIL
from PIL.Image import Image

file_body = <binary image data>
t_file = io.BytesIO(file_body)
img    = PIL.Image.open(t_file)

注意:cmets 提到了tempfile.SpooledTemporaryFile。这似乎应该有效,但由于某种原因它没有。

【讨论】:

    猜你喜欢
    • 2019-07-26
    • 2016-09-11
    • 2012-03-29
    • 2012-06-11
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多