简体   繁体   中英

How to pass Base64 image string from Flask Python code to HTML?

I have a Flask server and I want to render a base64 image in HTML page.

Flask Code:

new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
return render_template('perspective_result.html', img_data=new_image_string)

HTML CODE:

<img src="data:image/jpeg;base64,+img_data" alt="img_data"  id="imgslot"/>

I am getting the below error from browser console:

GET data:image/jpeg;base64,+img_data 0 ()

Where did I go wrong?

1. First Add A empty Image Tag Without A Source

2. Then With Javascript preprocess the base64 data string

3. update the Image src with updated base64 data

<img src="" id="img" alt="Chart" height="100" width="100">

<script>
    data = "{{data}}"
    data = data.replace("b&#39;", "") //to get rid of start curly brace code 
    data = data.replace("&#39;", "")  //to get rid of end curly bracecode 

    document.getElementById("img").src = "data:image/png;base64,"+data; // set src
</script>

<img src="data:image/jpeg;base64,{{ img_data }}" alt="img_data" id="imgslot"/>

这是我们可以解决这个问题的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM