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

问题描述 投票:0回答:2

我目前在 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)

我遇到了“图像类型无法识别”的异常。我知道我正在正确接收数据,因为如果我将图像写入文件然后打开文件,它就可以工作:

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

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

python string image sockets
2个回答
29
投票

我怀疑在将 StringIO 对象传递给 PIL 之前,您没有返回到缓冲区的开头。这是一些演示问题和解决方案的代码:


seek

确保在读取任何 StringIO 对象之前调用 
>>> 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

。否则,您将从缓冲区的末尾读取数据,这看起来像一个空文件,并且可能会导致您看到的错误。

    


7
投票
buff.seek(0)

,或者更好的是,使用数据初始化内存缓冲区

buff.seek(0)
    

© www.soinside.com 2019 - 2024. All rights reserved.