显示以二进制blob存储在模板中的图像 [英] Display image stored as binary blob in template
问题描述
send_file
或 render_template
,但是我没有得到图像或<只有获得图像,而不是模板的其余部分。如何在模板中显示二进制blob作为图像?class A(ndb.Model):
ndb.BlobProperty()
解决方案图像以字节存储。使用base64进行编码,并将其作为数据URI插入到呈现的html中。您可以将对象及其编码的图像传递给模板。
$ bfrom base64 import b64encode
(1)[b] [b] [b] [b] [b] [/ b] 0]
image = b64encode(obj.image)
return render_template('show_a.html',obj = obj,image = image)
< p> {{obj.x}}< br />
{{obj.y}}< / p>
< img src =data:; base64,{{image}}/>
这是次优的,因为数据uris每次渲染页面时发送,而客户端可以缓存图像文件。将图像文件存储在目录中,将路径存储在数据库中,然后单独提供图像文件将会更好。
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
orrender_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()
解决方案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) 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.
这篇关于显示以二进制blob存储在模板中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!