User Tools

Site Tools


python:inline_image

PIL - Display inline image

25.06.2013

Sometimes you need to display an image within an html page without saving to disk in advance.
This is done using a base64 encoding for the image:

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

with open('/tmp/example_image.png', 'rb') as image:
    img_tag = '<img src="data:image/png;base64,%s">' % image.read().encode('base64').replace('\n', '')



Specific case:

If you're using this good QR library, you can use the next 'trick' to get the base64 data:

import qrcode
qr = qrcode.make("qr_data")
 
# use an in-memory object to save
output = StringIO.StringIO()
qr.save(output)
 
# and the use getvalue() method to get the string
img_tag = '<img src="data:image/png;base64,%s">' % output.getvalue().encode('base64').replace('\n', '')

python/inline_image.txt · Last modified: 2013/06/25 15:50 by admin