【问题标题】:after PIL.Image.tostring() "cannot identify image file"在 PIL.Image.tostring() “无法识别图像文件”之后
【发布时间】:2015-05-31 02:16:08
【问题描述】:

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

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

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

现在我使用“PIL.Image”对象进行一些图像处理。我还想将这些对象转换为相同的string-format,以便它们可以在原始代码中使用。

这是我尝试过的。

>>> 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

【问题讨论】:

  • tostring() 方法不生成图像文件格式;它产生原始图像数据。您只能使用 ` 再次加载它。您的目标是什么,将图像以特定格式保存到内存中的文件对象?
  • 感谢您的极快响应。我已经通过编辑我的帖子回答了您的问题。

标签: python python-imaging-library stringio


【解决方案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))

【讨论】:

  • 谢谢。此代码正在运行。但是我不得不再次纠正可能的问题。我发现 imstr 应该是 string 对象而不是 StringIO 对象。请查看我上面的编辑以获取更多详细信息。
  • @BerndGit:更新以显示如何以字符串形式获取图像数据。
  • 酷。感谢您的大力帮助。
猜你喜欢
  • 2020-05-26
  • 2017-09-11
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多