Display image stored as binary blob in template

Tim picture Tim · Jul 11, 2015 · Viewed 9k times · Source

I have a model with an image stored as a binary blob. I want to display this image, along with other data about the object, in a template. Since the image is not a separate file, I can't figure out how to display it. I've tried setting headers, or using send_file or render_template, but I either don't get the image or only get the image and not the rest of the template. How can I display a binary blob as an image in a template?

class A(ndb.Model):
    id= ndb.IntegerProperty()
    x= ndb.StringProperty()
    y= ndb.StringProperty()
    image = ndb.BlobProperty()

Answer

davidism picture davidism · Jul 11, 2015

The image is stored as bytes. Encode it with base64 and insert it as a data URI in the rendered HTML. You can pass both the object and its encoded image to the template.

from base64 import b64encode

@app.route("/show/<int:id>")
def show(id):
    obj = A.query(A.id == id).fetch(1)[0]
    image = b64encode(obj.image).decode("utf-8")
    return render_template("show_a.html", obj=obj, image=image)
<p>{{ obj.x }}<br/>
{{ obj.y }}</p>
<img src="data:;base64,{{ image }}"/>

This is sub-optimal, because data URIs are sent every time the page is rendered, while an image file can be cached by the client. It would be better to store the image file in a directory, store the path in the database, and just serve the image file separately.