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

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

问题描述

我有一个模型,其图像存储为二进制 blob.我想在模板中显示此图像以及有关该对象的其他数据.由于图像不是单独的文件,我无法弄清楚如何显示它.我试过设置标题,或使用 send_filerender_template,但我要么没有得到图像,要么得到图像而不是模板的其余部分.如何在模板中将二进制 blob 显示为图像?

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

推荐答案

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

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 }}"/>

<小时>

这是次优的,因为每次呈现页面时都会发送数据 URI,而客户端可以缓存图像文件.最好将图片文件存放在一个目录中,将路径存放在数据库中,单独提供图片文件即可.


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天全站免登陆