【问题标题】:Convert PILLOW image into StringIO将 PILLOW 图像转换为 StringIO
【发布时间】:2014-09-15 05:48:41
【问题描述】:

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

【问题讨论】:

    标签: python python-imaging-library python-2.x stringio


    【解决方案1】:

    两种 cStringIO.StringIO() 对象,具体取决于实例的创建方式;一个用于阅读,另一个用于写作。这些不能互换。

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

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

    这是只是 cStringIO 模块所特有的; StringIO(纯python模块)没有这个限制。 documentation 使用别名 cStringIO.InputTypecStringIO.OutputType 来表示这些,并且有这样的说法:

    StringIO 模块的另一个区别是使用字符串参数调用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)
    

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多