如何在Python中从字符串创建图像
我现在在我的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类的时候做错了什么,但我不太确定。
2 个回答
7
你要么调用 buff.seek(0)
,要么更好的是,用数据来初始化内存缓冲区,像这样 StringIO.StringIO(data)
。
29
我怀疑你在把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
确保在读取任何StringIO对象之前,先调用 buff.seek(0)
。否则,你会从缓冲区的末尾读取数据,这样看起来就像是一个空文件,很可能就是导致你看到的错误的原因。