matplotlib将图表嵌入自动生成的HTML文件中

34

我想将由python matplotlib生成的图表嵌入到包含其他内容的html文件中。这个可行吗?

我的想法是将图表保存为png文件,然后使用<img>标签引用它。

我尝试使用的一些代码类似于:

import matplotlib.pyplot as plt
fig = plt.figure()
#plot sth
plt.savefig('test.png')

html = 'Some html head' + '<img src=\'test.png\'>' + 'Some more html'

with open('test.html','w') as f:
    f.write(html)

然而,这将生成两个文件而非一个文件,并且我没有服务器来托管png文件。是否可能将图形嵌入到html中?我该如何在python中实现它。

谢谢。


2
使用Base64图像怎么样?https://dev59.com/3Goy5IYBdhLWcg3wg-Um - Haochen Wu
Outlook IOS客户端无法显示以base64编码的图像,该图像包含在HTML格式的电子邮件中。是否有任何解决方法? - Edmund
2个回答

57

你可以将图像写入临时文件并使用 base64 编码,然后将编码后的 base64 图像嵌入到 HTML 中。现代大多数浏览器都可以正确地呈现该图像。

从您的代码中修改的简短示例如下:

import matplotlib.pyplot as plt
import base64
from io import BytesIO

fig = plt.figure()
#plot sth

tmpfile = BytesIO()
fig.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')

html = 'Some html head' + '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + 'Some more html'

with open('test.html','w') as f:
    f.write(html)

5
这对我起了作用,但我发现我需要再多做一步解码 encoded"<img src='data:image/png;base64,{}'>".format(encoded.decode("utf-8")) - Sean Chon
3
我通过使用以下代码解决了我的问题: encoded = base64.b64encode(tmpfile.getvalue()).decode('utf8') <img src='data:image/png;base64,{{}}'> - Hua Jia
太棒了的回答! - Barney Szabolcs
这个图像数据在哪里? - Amarnath Reddy Surapureddy
如何将矩阵数据转换为HTML中的图像,或者如何将矩阵数据嵌入HTML作为图像。 - Amarnath Reddy Surapureddy

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接