So I've got a setup of flask + jinja and I'm trying to display an image in an html file being rendered by jinja.
In Python I'm converting it into base64 and then sending it to the template. I'm then using an image tag to display the image.
<img src="data:image/jpeg;base64,{{ myimage }}">
I've confirmed that the Python encoding is correct, it displays as it should when I simply write an html file with the base64 embedded into it. Where it seems to fail is from the template modifying the output a little bit. In particular:
<img src=3D"data:;base64,/9j/4QAYR
...
baW4WqWj/2Q=3D=3D"/>
Jinja seems to be screwing around by adding the text 3D in a couple places where it looks like it shouldn't be. I haven't specified anything differently, and when I printed out myimage just as text, it came up the way I expected it to, starting with /9j and ending with /2Q==
I'm not sure if there's something with the way I'm interpreting it in Jijna or what, but it just doesn't load. I see the image src tag in the email source, but there's just nothing where I expect the image to be loaded.
Markup the variable myimage
as safe:
<img src="data:image/jpeg;base64,{{ myimage | safe }}">
Simple single file app (uses requests library):
from flask import Flask, render_template_string
import base64
import requests
app = Flask(__name__)
global _base64_encoded_image
@app.route('/')
def index():
_html_template = '''
<p><img src="data:image/jpeg;base64,{{ myimage | safe }}"><p>
<p><img src="data:image/jpeg;base64,{{ myimage | e }}"><p>
<p><img src="data:image/jpeg;base64,{{ myimage }}"><p>
'''
global _base64_encoded_image
return render_template_string(_html_template, myimage=_base64_encoded_image)
@app.before_first_request
def before_first_request():
global _base64_encoded_image
_url = "http://via.placeholder.com/200?text=Flask/Jinja2"
_r = requests.get(_url)
_base64_encoded_image = base64.b64encode(_r.content)
print _base64_encoded_image
if __name__ == '__main__':
app.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With