【发布时间】: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