Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image stored as binary blob in template

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()
like image 813
Tim Avatar asked Jul 11 '15 15:07

Tim


People also ask

Is binary same as blob?

BLOB Definition BLOB stands for a “Binary Large Object,” a data type that stores binary data. Binary Large Objects (BLOBs) can be complex files like images or videos, unlike other data strings that only store letters and numbers.

Is an image a blob?

A binary large object (BLOB or blob) is a collection of binary data stored as a single entity. Blobs are typically images, audio or other multimedia objects, though sometimes binary executable code is stored as a blob.


1 Answers

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.

like image 129
davidism Avatar answered Oct 26 '22 12:10

davidism