10

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?

Elad Alfassa
  • 103
  • 1
  • 1
  • 5

1 Answers1

19

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343