Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Imaging: load jpeg from memory

Tags:

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?

like image 574
Alexander Taran Avatar asked Jan 11 '12 14:01

Alexander Taran


People also ask

How do I import a JPEG into Python?

Images are typically in PNG or JPEG format and can be loaded directly using the open() function on Image class. This returns an Image object that contains the pixel data for the image as well as details about the image.

What does image load () do in Python?

image. load() function call will return a Surface object that has the image drawn on it. This Surface object will be a separate Surface object from the display Surface object, so we must blit (that is, copy) the image's Surface object to the display Surface object.

Is PIL and Pillow the same?

What is PIL/Pillow? PIL (Python Imaging Library) adds many image processing features to Python. Pillow is a fork of PIL that adds some user-friendly features.


1 Answers

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)

like image 83
jsbueno Avatar answered Sep 20 '22 11:09

jsbueno