Convert a BLOB stored in a database to an image on an HTML site

This is my first question.

I have users who upload their own image to the database. This image is stored as a BLOB.

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

In the part with which I am having problems, this BLOB is displayed as an image on the website when it is called.

Now only binary data is displayed, a lot of strange characters. I think this is a problem with the HTTP header. Now it is in:

print "Content-Type: text/html" 

I tried:

 print "Content-Type: image/jpeg" 

I use Python to connect to a database and write 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() 
+4
source share
3 answers

the image is stored in the database in binary format, so when it comes to the server, use the decoding function to return it to the image

 image.decode('base64') 

this will convert your frame into an image

+3
source

Depending on how you encode it, you can also use data URIs for the image. Something like this might work if they are encoded as base64 PNG.

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

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

+4
source

Well, you can either return the HTML response, and use a combination of existing answers, or simply return the image/jpeg response, and also upload 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 are trying to achieve.

0
source

All Articles