6

这是我的第一个问题。

我让用户将自己的图像上传到数据库。该图像存储为 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()
4

4 回答 4

6

根据其编码方式,您也可以只对图像使用数据 URI。如果它们被编码为 base64 PNG,这样的事情可能会起作用。

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

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

于 2013-04-29T14:11:43.360 回答
5

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

image.decode('base64')

这会将您的 blob 转换为图像

于 2013-04-29T14:00:25.757 回答
1

好吧,您可以返回一个 HTML 响应,并使用现有答案的组合,或者您可以只返回一个image/jpeg响应,然后将 BLOB 直接转储到标准输出,就像这样......

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

...但这取决于您要实现的目标。

于 2013-04-30T19:47:12.723 回答
1

这取决于你需要完成什么。

  1. HTML 页面上的单个图像。

    1.1 最好的方法是使用 Content-Type: image/jpeg (如果是 jpeg)

    import sys
    
    def showFile(blob):
        print "Content-Type: image/jpeg\r\n"
        sys.stdout.flush()
        print sys.stdout.buffer.write(image)
    
    def getFile():
        conn, cursor = getConnectionAndCursor()
        sql = 
        """
            select data
            from upload 
            where id=1
        """
        cursor.execute(sql)
        data = cursor.fetchone()
        blob = data[0]
    
        return blob
    
    if __name__ == "__main__":
    
        form = cgi.FieldStorage()
    
        if "show_file" in form: 
            image = getFile()
            showFile(image)
    

    为什么是最好的方法?因为您可以使用触发此脚本的请求的 url 作为 html 文件中图像标记的源

  2. 一个html页面上有多个图像。

    2.1 在base64中转换blob

     import base64
    
     blob = base64.b64encode(blob).decode('utf-8')
     # You need to decode it to get pure string and use it later in <img>
    

    转换后,您可以放置​​它。

     print(f"<img src="data:image/jpeg;base64,{blob}>")
    

注意:我在第二个示例中使用 python3.8。我假设您正在使用 cgi 模块。

于 2020-11-04T12:22:47.370 回答