无需保存即可获得PIL图像的二进制表示(Get Binary Representation of PIL Image Without Saving)

我正在编写一个强烈使用图像的应用程序。 它由两部分组成。 客户端部分是用Python编写的。 它对图像进行一些预处理,并通过TCP将它们发送到Node.js服务器。 预处理后,Image对象如下所示:

window = img.crop((x,y,width+x,height+y)) window = window.resize((48,48),Image.ANTIALIAS)

要通过套接字发送,我必须以二进制格式。 我现在在做的是:

window.save("window.jpg") infile = open("window.jpg","rb") encodedWindow = base64.b64encode(infile.read()) #Then send encodedWindow

但这是一个巨大的开销,因为我首先将图像保存到硬盘,然后再次加载以获取二进制格式。 这导致我的应用程序非常慢。 我阅读了PIL Image的文档,但没有发现它有用。

I am writing an application that uses images intensively. It is composed of two parts. The client part is written in Python. It does some preprocessing on images and sends them over TCP to a Node.js server. After preprocessing, the Image object looks like this:

window = img.crop((x,y,width+x,height+y)) window = window.resize((48,48),Image.ANTIALIAS)

To send that over socket, I have to have it in binary format. What I am doing now is:

window.save("window.jpg") infile = open("window.jpg","rb") encodedWindow = base64.b64encode(infile.read()) #Then send encodedWindow

This is a huge overhead, though, since I am saving the image to the hard disk first, then loading it again to obtain the binary format. This is causing my application to be extremely slow. I read the documentation of PIL Image, but found nothing useful there.

最满意答案

根据文件,(在effbot.org):

“您可以使用文件对象而不是文件名。在这种情况下,您必须始终指定格式。文件对象必须实现seek,tell和write方法,并以二进制模式打开。”

这意味着您可以传递StringIO对象。 写入并获取大小而不会碰到磁盘。

喜欢这个:

s = StringIO.StringIO() window.save(s, "jpg") encodedWindow = base64.b64encode(s.getvalue())

According to the documentation, (at effbot.org):

"You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode."

This means you can pass a StringIO object. Write to it and get the size without ever hitting the disk.

Like this:

s = StringIO.StringIO() window.save(s, "jpg") encodedWindow = base64.b64encode(s.getvalue())

更多推荐