How to send image generated by PIL to browser?

前端 未结 5 1982
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 22:16

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 ?

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 22:54

    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
    

提交回复
热议问题