我正在编写一个程序,可以接收各种常见图像格式的图像,但需要检查它们在一个一致的格式。什么图像格式并不重要,主要是它们都是一样的。因为我需要转换图像格式,然后继续处理图像,所以我不想将其保存到磁盘;只需转换它并继续。下面是我使用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用同样的结果。关于如何处理这个问题有什么建议吗?
根据实例的创建方式,有两种类型的对象:一种用于读取,另一种用于写入。你不能交换这些。
当您创建一个空的
cStringIO.StringIO()
对象时,您确实得到了一个cStringIO.StringO
(注意末尾的O
)类,它只能充当输出的角色,即write to。相反,使用初始内容创建一个对象会生成一个
cStringIO.StringI
对象(以I
结尾作为输入),您永远无法对其进行写入,只能从中读取。这对于} 和^{} 来表示这些,并有这样的含义:
cStringIO
模块来说是特别的;StringIO
(纯python模块)没有这个限制。documentation使用别名^{使用
cStringIO.StringO.getvalue()
从输出文件中获取数据:您可以使用^{} 代替,但在写入后需要倒带:
相关问题 更多 >
编程相关推荐