如何在python中从字符串创建图像

Ada*_* A. 17 python sockets string image

我目前在Python程序中从二进制数据字符串创建图像时遇到问题.我通过套接字接收二进制数据,但是当我尝试我在这里阅读的方法时,如下所示:

buff = StringIO.StringIO() #buffer where image is stored
#Then I concatenate data by doing a 
buff.write(data) #the data from the socket
im = Image.open(buff)
Run Code Online (Sandbox Code Playgroud)

我对"图像类型未识别"的效果有异常.我知道我正在接收数据,因为如果我将图像写入文件然后打开文件它会工作:

buff = StringIO.StringIO() #buffer where image is stored
buff.write(data) #data is from the socket
output = open("tmp.jpg", 'wb')
output.write(buff)
output.close()
im = Image.open("tmp.jpg")
im.show()
Run Code Online (Sandbox Code Playgroud)

我想我在使用StringIO类时可能做错了但是我不确定

Ste*_*lla 29

我怀疑你在seek将StringIO对象传递给PIL之前没有回到缓冲区的开头.这里有一些代码演示了问题和解决方案:

>>> buff = StringIO.StringIO()
>>> buff.write(open('map.png', 'rb').read())
>>> 
>>> #seek back to the beginning so the whole thing will be read by PIL
>>> buff.seek(0)
>>>
>>> Image.open(buff)
<PngImagePlugin.PngImageFile instance at 0x00BD7DC8>
>>> 
>>> #that worked.. but if we try again:
>>> Image.open(buff)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python25\lib\site-packages\pil-1.1.6-py2.5-win32.egg\Image.py", line 1916, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file
Run Code Online (Sandbox Code Playgroud)

确保buff.seek(0)在读取任何StringIO对象之前调用.否则你将从缓冲区的末尾读取,这看起来像一个空文件,可能会导致你看到的错误.

  • 你可以改为`buff = StringIO.StringIO(open('map.png','rb').read())`.不再需要`seek()`了. (3认同)

Den*_*ach 7

您可以使用数据调用buff.seek(0)或更好地初始化内存缓冲区StringIO.StringIO(data).