Alexander Taran
Alexander Taran

Reputation: 1036

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?

Upvotes: 25

Views: 26548

Answers (2)

jsbueno
jsbueno

Reputation: 110696

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)

Upvotes: 41

Scott Hunter
Scott Hunter

Reputation: 49920

Use StringIO so Image can access your data as if it were a file.

Upvotes: 0

Related Questions