Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Binary Representation of PIL Image Without Saving

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.

like image 677
JackOrJones Avatar asked Dec 26 '14 01:12

JackOrJones


People also ask

Is Pil image RGB or BGR?

The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference.

How do you display the PIL of an image in Python?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image. Once the program execution is completed, the temporary file will be deleted.


1 Answers

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())
like image 167
swstephe Avatar answered Oct 30 '22 22:10

swstephe