将枕头图像转换为StringI

2024-09-27 23:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,可以接收各种常见图像格式的图像,但需要检查它们在一个一致的格式。什么图像格式并不重要,主要是它们都是一样的。因为我需要转换图像格式,然后继续处理图像,所以我不想将其保存到磁盘;只需转换它并继续。下面是我使用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用同样的结果。关于如何处理这个问题有什么建议吗?


Tags: theinpy图像imagebufferline图像格式
1条回答
网友
1楼 · 发布于 2024-09-27 23:26:41

根据实例的创建方式,有两种类型的对象:一种用于读取,另一种用于写入。你不能交换这些。

当您创建一个空的cStringIO.StringIO()对象时,您确实得到了一个cStringIO.StringO(注意末尾的O)类,它只能充当输出的角色,即write to。

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

这对于cStringIO模块来说是特别的;StringIO(纯python模块)没有这个限制。documentation使用别名^{}^{}来表示这些,并有这样的含义:

Another difference from the StringIO module is that calling StringIO() 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 as StringI and StringO.

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

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

您可以使用^{}代替,但在写入后需要倒带:

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)

相关问题 更多 >

    热门问题