How to send image generated by PIL to browser?

user795243 picture user795243 · Oct 24, 2011 · Viewed 41.2k times · Source

I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk.

Any idea how to do this ?

Answer

Mr. Mr. picture Mr. Mr. · Apr 16, 2012

Here's a version without any temp files and the like (see here):

def serve_pil_image(pil_img):
    img_io = StringIO()
    pil_img.save(img_io, 'JPEG', quality=70)
    img_io.seek(0)
    return send_file(img_io, mimetype='image/jpeg')

To use in your code simply do

@app.route('some/route/')
def serve_img():
    img = Image.new('RGB', ...)
    return serve_pil_image(img)