user1038085 user1038085 - 15 days ago 7
Python Question

Python Imaging: load jpeg from memory

The problem is to load jpeg-encoded image from memory.

I receive a string from socket:

jpgdata = self.rfile.read(sz)


and I know that this is jpeg-encoded image.

I need to decode it.
The most stupid solution is:

o = open("Output/1.jpg","wb")
o.write(jpgdata)
o.close()
dt = Image.open("Output/1.jpg")


The question is how to do the same thing in-memory?

Answer

PIL's Image.open object accepts any file-like object. That means you can wrap your Image data on a StringIO object, and pass it to Image.Open

from cStringIO import StringIO
file_jpgdata = StringIO(jpgdata)
dt = Image.open(file_jpgdata)

Or, try just passing self.rfile as an argument to Image.open - it might work just as well. (That is for Python 2 - for Python 3 use from io import BytesIO)