在PIL.Image.tostring()"之后无法识别图像文件"

时间:2015-03-26 21:18:16

标签: python python-imaging-library stringio

我想使用string来存储图像数据。

背景:在代码的其他部分,我加载了从网上下载的图像,并使用

存储为string
imgstr = urllib2.urlopen(imgurl).read()
PIL.Image.open(StringIO.StringIO(imstr))

现在我使用' PIL.Image'进行一些图像处理。宾语。我还希望以相同的string - 格式转换这些对象,以便它们可以在原始代码中使用。

这就是我的尝试。

>>> import PIL
>>> import StringIO

>>> im = PIL.Image.new("RGB", (512, 512), "white")
>>> imstr=im.tostring()

>>> newim=PIL.Image.open(StringIO.StringIO(imstr))
Traceback (innermost last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2006, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

我在网上发现了这可能会发生的提示。例如Python PIL: how to write PNG image to string 但是,我无法为我的示例代码提取正确的解决方案。

接下来的尝试是:

>>> imstr1 = StringIO.StringIO()
>>> im.save(imstr1,format='PNG')
>>> newim=PIL.Image.open(StringIO.StringIO(imstr1))
Traceback (innermost last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2006, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

1 个答案:

答案 0 :(得分:1)

您不必将现有的StringIO对象包装在另一个此类对象中; imstr1 已经一个文件对象。你所要做的就是回到起点:

imstr1 = StringIO.StringIO()
im.save(imstr1, format='PNG')
imstr1.seek(0)
newim = PIL.Image.open(imstr1)

您可以使用StringIO.getvalue() methodStringIO对象中获取字节串:

imstr1 = StringIO.StringIO()
im.save(imstr1, format='PNG')
imagedata = imstr1.getvalue()

然后您可以稍后将其重新加载到相反方向的PIL.Image对象中:

newim = PIL.Image.open(StringIO.StringIO(imagedata))