我正在编写一个程序,它可以接收各种常见图像格式的图像,但需要以一种一致的格式检查所有图像。什么图像格式并不重要,主要是它们都是相同的。因为我需要转换图像格式然后继续处理图像,所以我不想将它保存到磁盘;只需转换它并继续。这是我使用 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.StringIO()
对象时,您实际上得到了一个cStringIO.StringO
(注意O
最后)类,它只能作为输出,即写入。
相反,用初始内容创建一个对象会生成一个 cStringIO.StringI
对象(以 I
结尾用于输入),您永远不能写入它,只能从中读取。
这仅 cStringIO
模块是特别的; StringIO
(纯 python 模块)没有这个限制。 documentation使用别名 cStringIO.InputType
和 cStringIO.OutputType
对于这些,有话要说:
Another difference from the
StringIO
module is that callingStringIO()
with a string parameter creates a read-only object. Unlike an object created without a string parameter, it does not have write methods. These objects are not generally visible. They turn up in tracebacks asStringI
andStringO
.
使用 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)
关于python - 将 PILLOW 图像转换为 StringIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920728/