将存储在数据库中的BLOB转换为HTML网站上的图像

2024-04-20 08:43:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个问题。

我让用户上传他们自己的图片到数据库。 该图像存储为一个BLOB。

我成功地做到了。 我在数据库中使用MySQL。

我遇到的问题是,当网站被调用时,我会将这个BLOB显示为一个图像。

现在只有二进制数据,显示了很多奇怪的符号。我认为这是HTTP头的问题。现在它在:

print "Content-Type: text/html"

我试过:

print "Content-Type: image/jpeg"

我使用Python连接数据库并编写HTML。

编辑:代码:

def showFile():

    # do SQL to retrieve blob where filename
    conn, cursor = getConnectionAndCursor()
    sql = """
    select data
    from upload 
    where id=1
    """
    cursor.execute(sql)
    data = cursor.fetchone()
    blob = data[0]

    print "<hr>"
    print "This is what I'm trying"
    print """<img  src="data:image/jpeg;base64,%s/>""" % data

######################################################################
if __name__ == "__main__":

    form = cgi.FieldStorage()

    if "show_file" in form:
        print "Content-Type: text/html"
        print 
        printHeaders("Image upload example")
        showFile()
        printFooter()

Tags: text图像image数据库datahtmltypecontent
3条回答

根据它的编码方式,您也可以只使用图像的数据URI。如果它们被编码为base64 png,这种方法可能会奏效。

<img  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

正如@Alok所说,您可能需要首先将它从二进制blob转换为base64,然后使用数据URI。

好吧,您可以返回一个HTML响应,并使用现有答案的组合,也可以只返回一个image/jpeg响应,并将BLOB直接转储到stdout,如下所示。。。

def showFile():

    # do SQL to retrieve blob where filename
    conn, cursor = getConnectionAndCursor()
    sql = """
    select data
    from upload 
    where id=1
    """
    cursor.execute(sql)
    data = cursor.fetchone()
    blob = data[0]

    print blob

if __name__ == "__main__":

    form = cgi.FieldStorage()

    if "show_file" in form:
        print "Content-Type: image/jpeg"
        print 
        showFile()

……但这取决于你想达到什么目标。

图像以二进制格式存储在数据库中,因此一旦到达服务器,就使用解码功能将其恢复到图像

image.decode('base64')

这将把你的blob转换成图像

相关问题 更多 >