【问题标题】:Displaying a blob in a template - Convert binary data into an image in a template在模板中显示 blob - 将二进制数据转换为模板中的图像
【发布时间】:2016-06-22 20:07:27
【问题描述】:

我目前使用 sqlite 作为我的数据库。现在我的一个表包含一个基本上是图像的 blob 数据。由于某些原因,我没有使用 Django 的 ORM 并直接从我的数据库中读取和写入。现在我想知道如何将这个二进制数据转换/呈现为我的模板中的图像?

目前做显示图像我会做这样的事情

<img src=“pic.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

但在这种情况下,图像是在运行时构建的,并且图像的数据正在从视图传递到模板。

我在数据库中存储图像的方式是这样的

def insert_Sample_imageInDB():
    picture_file="pic.jpg"
    cursor = connection.cursor()
    with open(picture_file, 'rb') as input_file:
        ablob = input_file.read()
        base = os.path.basename(picture_file)
        afile, ext = os.path.splitext(base)
        sql = "INSERT INTO ImageTable (image_col) VALUES(%s)"
        cursor.execute(sql, [sqlite3.Binary(ablob)])
        cursor.close()

【问题讨论】:

  • 是base64的数据数组吗?
  • @Sayse 我不确定。但是,我将字符串插入数据库的方式如上所示。我使用的是 python 3,默认编码是一个字节,在 python 2 中是字符串。
  • 好的,你已经写好了,因为你有 files 二进制数据而不是图像,所以你需要打开文件流并检索 image 的 base64 数组,在这种情况下,如何在 img html 标签中加载 base64 图像非常简单
  • 那么您是否建议将二进制数据转换为 base64 ?然后显示图像?
  • ok 会试一试并回复

标签: django sqlite django-templates


【解决方案1】:

所以我基本上将图像作为 base64 编码字符串存储在我的数据库中,然后使用以下内容在我的视图中显示该图像

 <img alt="Embedded Image" src="data:image/png;base64,{{ rslt }}" style="width:50px;height:50px;"/>

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 2020-02-07
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多