Render image without saving

后端 未结 3 723
梦谈多话
梦谈多话 2021-01-22 20:44

I want to get an image from user, work with it at beckend and render result back to user. Is it possible to do without saving image on disk?

my view:

cla         


        
3条回答
  •  醉酒成梦
    2021-01-22 21:16

    The problem is that returning a page to the user would normally involve two requests: one for the HTML page, and one for the image itself as referenced by an img tag in that HTML. But as you say, without storing it anywhere in the meantime, the image would be lost.

    There is an alternative: you can use a data uri to include the actual data for the image inline in the html. That means you won't have to persist it across requests, as everything will be returned at one. Data uris are supported in most browsers, including ie8+.

    You can format the data like this, for example:

    from base64 import b64encode
    
    encoded = b64encode(img_data)
    mime = "image/jpeg"
    uri = "data:%s;base64,%s" % (mime, encoded)
    

    And use it directly in the template:

    
    

提交回复
热议问题