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

Is it possible to create a function image tag in html from a BytesIO buffer? I would like to do something in this direction:

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>" 

You may need to reformat the buffer value in some way or modify the contents of the 'src' data. Thanks.

+4
source share
2 answers

Problem resolved:

at the end of the code above, do the following:

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

If you work with Flask , you can return the image to UTF-8 and play with it.

 figfile = BytesIO() plt.savefig(figfile, format='png') plt.clf() # this will clear the image figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) return figdata_png.decode('UTF-8') 

Remember to mention this in the <img/> tags. This is for implementation in Flask .

0
source

Source: https://habr.com/ru/post/1490511/


All Articles