Converting BLOB, stored on a database, to an image on an HTML website

我怕爱的太早我们不能终老 提交于 2019-12-12 10:52:43

问题


This is my first question.

I am having users upload their own image to a database. That image is stored as a BLOB.

I was able to do this successfully. I am using MySQL for the database.

The part I am having trouble with is displaying that BLOB as an image on the website when its called upon.

Right now only the Binary data, lots of weird symbols are being displayed. I think its a problem with the HTTP header. Right now its in :

print "Content-Type: text/html"

I've tried:

print "Content-Type: image/jpeg"

I am using Python to connect with the database and write the HTML.

Edit: Code:

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

回答1:


image is stored in database in binary format so once it comes to server using decode function to get it back to image

image.decode('base64')

this will convert your blob to image




回答2:


Depending on how its encoded, you can also possibly just use a Data URI for the image. Something like this might work if they are encoded as base64 PNGs.

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

As @Alok says, you might need to first convert it from binary blob to base64, then use the Data URI.




回答3:


Well, you can either return an HTML response, and use a combination of the existing answers, or you can just return an image/jpeg response, and dump the BLOB directly to stdout, with something like this...

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

...but it depends on what you're trying to achieve.



来源:https://stackoverflow.com/questions/16279856/converting-blob-stored-on-a-database-to-an-image-on-an-html-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!