How to send image generated by PIL to browser?

前端 未结 5 1977
佛祖请我去吃肉
佛祖请我去吃肉 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:51

    I was also struggling in the same situation. Finally, I have found its solution using a WSGI application, which is an acceptable object for "make_response" as its argument.

    from Flask import make_response
    
    @app.route('/some/url/to/photo')
    def local_photo():
        print('executing local_photo...')
        with open('test.jpg', 'rb') as image_file:
            def wsgi_app(environ, start_response):
                start_response('200 OK', [('Content-type', 'image/jpeg')])
                return image_file.read()
            return make_response(wsgi_app)
    

    Please replace "opening image" operations with appropriate PIL operations.

提交回复
热议问题