显示以二进制blob存储在模板中的图像 [英] Display image stored as binary blob in template

查看:123
本文介绍了显示以二进制blob存储在模板中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像存储为一个二进制blob的模型。我想在模板中显示这个图像,以及关于对象的其他数据。由于图像不是一个单独的文件,我无法弄清楚如何显示它。我已经尝试设置标题,或者使用 send_file render_template ,但是我没有得到图像或<只有获得图像,而不是模板的其余部分。如何在模板中显示二进制blob作为图像?

  class A(ndb.Model):
ndb.BlobProperty()

解决方案

图像以字节存储。使用base64进行编码,并将其作为数据URI插入到呈现的html中。您可以将对象及其编码的图像传递给模板。

  from 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)
$ b

 < 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 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()

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆