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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With