Get binary representation of a PIL image without saving

I am writing an application that makes heavy use of images. It consists of two parts. The client part is written in Python. It does some image preprocessing and sends them over TCP to the 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 this socket, I have to have it in binary format. Now I am doing the following:

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

This is a huge overhead, however, since I first save the image to my hard drive and then upload it again to get the binary format. This causes my application to run very slowly. I read the PIL Image documentation but found nothing useful there.

+4
source share
1 answer

According to the documentation, (on the effbot.org website):

"You can use the file object instead of the file name. In this case, you should always specify the format. The file object must implement the search, pointing and writing methods and open in binary mode."

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

Like this:

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

Source: https://habr.com/ru/post/1569009/


All Articles