将 matplotlib png 转换为 base64 以在 html 模板中查看

2024-05-09

背景

你好,我正在尝试制作一个简单的网络应用程序,按照教程计算阻尼振动方程,并将结果的 png 返回到 html 页面,然后将其转换为 Base64 字符串。

Problem

该应用程序运行正常,只是在计算结果时返回损坏的图像图标,可能是因为 Base64 字符串无效。

故障排除

我已经使用在线转换器将另一个 png 图像转换为 Base64 字符串并使用<img src="data:image/png;base64, BASE64_STRING"/>即可成功显示图像。我相信模板的格式正确。我还阅读了其他答案here https://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask and here https://stackoverflow.com/questions/28091129/what-is-the-difference-among-idioms-for-serving-a-matplotlib-image-with-flask并尝试实施这些但没有成功。

相关代码

这是返回图像字符串的地方

from numpy import exp, cos, linspace
import matplotlib.pyplot as plt


def damped_vibrations(t, A, b, w):
    return A*exp(-b*t)*cos(w*t)


def compute(A, b, w, T, resolution=500):
    """Return filename of plot of the damped_vibration function."""
    t = linspace(0, T, resolution+1)
    u = damped_vibrations(t, A, b, w)
    plt.figure()  # needed to avoid adding curves in plot
    plt.plot(t, u)
    plt.title('A=%g, b=%g, w=%g' % (A, b, w))

    from io import BytesIO
    figfile = BytesIO()
    plt.savefig(figfile, format='png')
    figfile.seek(0)  # rewind to beginning of file
    import base64
    #figdata_png = base64.b64encode(figfile.read())
    figdata_png = base64.b64encode(figfile.getvalue())
    return figdata_png

这是图像显示的地方

{% if result != None %}
<img src="data:image/png;base64,{{ result }}"\>
{% endif %}

如果需要,我也可以提供控制器文件。谢谢你的帮助!


模板中数据的开头提供了有关正在发生的情况的线索。&#39;是单引号的 HTML 实体'。结合前面的b,b',它看起来像是字节字符串的表示,而不是字符串的内容。

在尝试使用 Jinja 渲染它们之前,将字节字符串解码为字符串。

render_template('result.html', result=figdata_png.decode('utf8'))

Jinja 呈现字符串表示中的对象数{{ }}。字节字符串的字符串表示形式包括b''以将其与 Unicode 字符串区分开来。所以你必须解码才能直接显示它们的值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 matplotlib png 转换为 base64 以在 html 模板中查看 的相关文章

随机推荐