User Tools

Site Tools


PIL - Display inline image


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">' %'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()
# 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