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

Converting matplotlib png to base64 for viewing in html template

背景

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

问题

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

疑难解答

我已经使用在线转换器将另一个 png 图像转换为 Base64 字符串,并使用 <img src="data:image/png;base64, BASE64_STRING"/> 成功显示图像。我相信模板的格式正确。我还阅读了其他 SO 答案 here and 并尝试实施这些答案但没有成功。

相关代码

这里是返回图片字符串的地方

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 字符串。所以你必须解码才能直接显示它们的值。

尝试将 meta charset="utf-8" 部分添加到模板的 HEAD 部分。这对我有用:-)