Render image without saving

后端 未结 3 695
梦谈多话
梦谈多话 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:11

    This answer is inspired by @Daniel Roseman answer

    write the image to BytesIO()

    from PIL import Image  
    img = Image.open("image.jpg") 
    data = io.BytesIO()
    img.save(data, "JPEG") # just an example, load the image into BytesIO any way you like.
    

    encode img into base64

    encoded_img = base64.b64encode(data.getvalue())
    

    decode img in context, as well as setting content_type

    decoded_img = encoded_img.decode('utf-8')
    img_data = f"data:image/jpeg;base64,{decoded_img}"
    

    render your template

    return render(request, "index.html", img_data=img_data)
    

    in your HTML template

    you can check also https://buraksenol.medium.com/pass-images-to-html-without-saving-them-as-files-using-python-flask-b055f29908a

提交回复
热议问题