如何在python中从字符串创建图像 [英] How to create an image from a string in python
问题描述
我目前在Python程序中使用二进制数据字符串创建图像时遇到问题。我通过套接字接收二进制数据但是当我尝试我在这里上阅读的方法时,就像这样:
I'm currently having trouble creating an image from a binary string of data in my Python program. I receive the binary data via a socket but when I try the methods I read about on here like this:
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)
我得到图像类型无法识别效果的例外。我知道我正在接收数据,因为如果我将图像写入文件然后打开文件就可以了:
I get an exception to the effect of "image type not recognized". I know that I am receiving the data correctly because if I write the image to a file and then open a file it works:
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类时可能做错了但是我不确定
I figure I am probably doing something wrong in using the StringIO class but I'm not sure
推荐答案
我怀疑你不是寻找
- 在传递StringIO对象之前回到缓冲区的开头到PIL。以下是一些演示问题和解决方案的代码:
I suspect that you're not seek
-ing back to the beginning of the buffer before you pass the StringIO object to PIL. Here's some code the demonstrates the problem and solution:
>>> 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)
。否则你将从缓冲区的末尾读取,这看起来像一个空文件,可能会导致你看到的错误。
Make sure you call buff.seek(0)
before reading any StringIO objects. Otherwise you'll be reading from the end of the buffer, which will look like an empty file and is likely causing the error you're seeing.
这篇关于如何在python中从字符串创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!