将PILLOW图像转换为StringIO

9

我正在编写一个程序,可以接收多种常见的图像格式,但需要以一种统一的格式检查它们。实际上,图像格式并不重要,主要是所有图像都是相同的格式。由于我需要转换图像格式,然后继续处理图像,因此我不想将其保存到磁盘上,只需转换并继续进行。以下是使用StringIO的尝试:

image = Image.open(cStringIO.StringIO(raw_image)).convert("RGB")
cimage = cStringIO.StringIO() # create a StringIO buffer to receive the converted image
image.save(cimage, format="BMP") # reformat the image into the cimage buffer
cimage = Image.open(cimage)

它会返回以下错误信息:
Traceback (most recent call last):
  File "server.py", line 77, in <module>
    s.listen_forever()
  File "server.py", line 47, in listen_forever
    asdf = self.matcher.get_asdf(data)
  File "/Users/jedestep/dev/hitch-py/hitchhiker/matcher.py", line 26, in get_asdf
    cimage = Image.open(cimage)
  File "/Library/Python/2.7/site-packages/PIL/Image.py", line 2256, in open
    % (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringO object at 0x10261d810>

我也尝试过使用io.BytesIO,但结果相同。有什么建议如何处理这个问题吗?
1个回答

21

cStringIO.StringIO()对象有两种类型,取决于实例创建的方式; 一个用于仅读取,另一个用于写入。您不能交换它们。

当您创建一个空的cStringIO.StringIO()对象时,您实际上获得了一个cStringIO.StringO类(请注意结尾处的O),它只能作为输出,即写入。

相反,使用初始内容创建对象会产生一个cStringIO.StringI对象(以I结尾以表示输入),您永远无法对其进行编写,只能从中读取。

这仅适用于cStringIO模块;StringIO(纯Python模块)没有此限制。 文档使用别名cStringIO.InputTypecStringIO.OutputType来表示它们,并且有以下说明:

StringIO()与字符串参数一起调用的另一个区别是它创建了一个只读对象。不像没有字符串参数创建的对象,它没有写入方法。这些对象通常不可见。它们以StringIStringO的形式出现在跟踪中。

使用cStringIO.StringO.getvalue()从输出文件中获取数据:

# replace cStringIO.StringO (output) with cStringIO.StringI (input)
cimage = cStringIO.StringIO(cimage.getvalue())
cimage = Image.open(cimage)

你可以使用 io.BytesIO() 代替,但是在写入后需要倒回:

image = Image.open(io.BytesIO(raw_image)).convert("RGB")
cimage = io.BytesIO()
image.save(cimage, format="BMP")
cimage.seek(0)  # rewind to the start
cimage = Image.open(cimage)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接