将PILLOW图像转换为StringIO

Jed*_*tep 8 python python-2.x stringio python-imaging-library

我正在编写一个程序,可以接收各种常见图像格式的图像,但需要以一致的格式检查它们.什么图像格式并不重要,主要是因为它们都是相同的.由于我需要转换图像格式然后继续使用图像,我不想将其保存到磁盘; 只需将其转换并继续.这是我使用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)
Run Code Online (Sandbox Code Playgroud)

它返回以下错误:

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>
Run Code Online (Sandbox Code Playgroud)

我也尝试过与io.BytesIO相同的结果.关于如何处理这个的任何建议?

Mar*_*ers 20

根据实例的创建方式,有两种类型cStringIO.StringIO()对象; 一个只是阅读,另一个是写作.你不能互换这些.

当你创建一个 cStringIO.StringIO()对象时,你真的得到一个cStringIO.StringO(注意到O最后)类,它只能作为输出,即写入.

相反,使用初始内容创建一个会生成一个cStringIO.StringI对象(以I输入结尾),您永远不能写入它,只能从中读取.

仅适用cStringIO模块; 该StringIO(纯Python模块)不具有此限制.该文件使用别名cStringIO.InputType,并cStringIO.OutputType为这些了,有这样一段话:

StringIO模块的另一个区别是StringIO()使用字符串参数调用会创建一个只读对象.与没有字符串参数创建的对象不同,它没有写入方法.这些对象通常不可见.他们在回溯调高为StringIStringO.

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

# replace cStringIO.StringO (output) with cStringIO.StringI (input)
cimage = cStringIO.StringIO(cimage.getvalue())
cimage = Image.open(cimage)
Run Code Online (Sandbox Code Playgroud)

可以使用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)
Run Code Online (Sandbox Code Playgroud)