Search code examples
pythonstreamingpython-imaging-libraryflasktemporary-files

How to send image generated by PIL to browser?


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 ?


Solution

  • First, you can save the image to a tempfile and remove the local file (if you have one):

    from tempfile import NamedTemporaryFile
    from shutil import copyfileobj
    from os import remove
    
    tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg')
    pilImage = open('/tmp/myfile.jpg','rb')
    copyfileobj(pilImage,tempFileObj)
    pilImage.close()
    remove('/tmp/myfile.jpg')
    tempFileObj.seek(0,0)
    

    Second, set the temp file to the response (as per this stackoverflow question):

    from flask import send_file
    
    @app.route('/path')
    def view_method():
        response = send_file(tempFileObj, as_attachment=True, attachment_filename='myfile.jpg')
        return response