python:给定一个BytesIO缓冲区,用html生成img标记?

2024-04-25 17:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以从字节缓冲区生成html格式的功能性图像标记?我想按照以下思路做些事情:

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

可能需要以某种方式重新格式化缓冲区的值,或更改“src”数据的内容。谢谢您。在


Tags: ioimportsrcimgdata字节pngmatplotlib
2条回答

解决问题:

在上述代码末尾,请执行以下操作:

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

如果您正在使用Flask,那么您可以返回图像的UTF-8格式并使用它。在

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')

记住在<img/>标记中提到它。这将在Flask中实现。在

相关问题 更多 >