3

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?

3
  • 3
    Please read flask.pocoo.org/docs/1.0/quickstart/#rendering-templates carefully. First img_data is inside the string and you are not using template syntax. Commented Feb 11, 2019 at 8:07
  • See the comment I added to my answer on your prior question about this. Commented Feb 12, 2019 at 4:24
  • 1
    If you want to pass a variable to a template you need to put it between curly brackets. Do you have something like {{ img_data }} in your template? Commented Feb 12, 2019 at 15:39

2 Answers 2

8

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

This is the way we can solve this.

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is underated. Worked perfectly.
2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.