Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Given a BytesIO buffer, generate img tag in html?

Is it possible to generate a functional image tag in html from a BytesIO buffer? I'd like to do something along these lines:

import matplotlib
matplotlib.use('Agg') 
import pylab
import Image
import io

temp_data = {'x':[1,2,3],'y':[2,4,5]}
pylab.plot(temp_data['x'], temp_data['y'])

img_buffer = io.BytesIO()
pylab.savefig(img_buffer, format = 'png')
img_buffer.seek(0)

img_tag = "<img src='data:image/png;base64,'" + img_buffer.getvalue() + "</img>"

May be necessary to re-format the value of the buffer in some way, or to change the content of the 'src' data. Thank you.

like image 261
Lamps1829 Avatar asked Jul 09 '13 15:07

Lamps1829


1 Answers

Python2

Towards the end of the code above, do this

import base64
img_tag = "<img src='data:image/png;base64," + base64.b64encode(img_buffer.getvalue()) + "'/>"

Python3

For this to work in python3 you will need to decode the bytes variable generated from base64.b64encode using str.decode method into a string as follows

import base64
str_equivalent_image = base64.b64encode(img_buffer.getvalue()).decode()
img_tag = "<img src='data:image/png;base64," + str_equivalent_image + "'/>"
like image 106
Lamps1829 Avatar answered Sep 24 '22 23:09

Lamps1829