Python Imaging: load jpeg from memory

Alexander Taran picture Alexander Taran · Jan 11, 2012 · Viewed 17.3k times · Source

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

jsbueno picture jsbueno · Jan 11, 2012

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 io import BytesIO
file_jpgdata = BytesIO(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 3 - for Python 2 use from cStringIO import StringIO as BytesIO)