Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: process image and save to file stream

I need to process an image (apply filters and other transformation) using python and then serve it to the user using HTTP. Right now, I'm using BaseHTTPServer and PIL.

Problem is, PIL can't write directly into file streams, so I have to write into a temporary file, and then read this file so I could send it to the user of the service.

Are there any image processing libraries for python that can output JPEG directly to I/O (file-like) streams? is there a way to make PIL do that?

like image 552
Elad Alfassa Avatar asked Jan 13 '13 14:01

Elad Alfassa


People also ask

How do I save a processed image in Python?

The PIL module is used for storing, processing, and displaying images in Python. To save images, we can use the PIL. save() function. This function is used to export an image to an external file.

How do I save a PNG in Python?

imwrite() saves the image file to the specified path. The first parameter is the path where you want to save the file, and the second parameter is the image to be saved.

How do I import a picture into PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).


1 Answers

Use the in-memory binary file object io.BytesIO:

from io import BytesIO

imagefile = BytesIO()
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()

This is available on both Python 2 and Python 3, so should be the preferred choice.

On Python 2 only, you can also use the in-memory file object module StringIO, or it's faster C-coded equivalent cStringIO:

from cStringIO import StringIO

imagefile = StringIO()  # writable object

# save to open filehandle, so specifying the expected format is required
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()

StringIO / cStringIO is the older, legacy implementation of the same principle.

like image 106
Martijn Pieters Avatar answered Oct 12 '22 06:10

Martijn Pieters