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

Rod*_*ele 21 html python base64 matplotlib flask

背景

您好,我正在尝试创建一个简单的Web应用程序,按照教程计算一个阻尼振动方程,并在将其转换为Base64字符串后将结果的png返回到html页面.

问题

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

故障排除

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

相关代码

这是返回图像字符串的位置

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
Run Code Online (Sandbox Code Playgroud)

这是显示图像的位置

{% if result != None %}
<img src="data:image/png;base64,{{ result }}"\>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

dav*_*ism 17

模板中数据的开头给出了发生了什么的线索. &#39;是单引号的HTML实体'.结合前面的b,b'它看起来像是字节串的表示,而不是字符串的内容.

在尝试使用Jinja呈现字节字符串之前,将字节字符串解码为字符串.

render_template('result.html', result=figdata_png.decode('utf8'))
Run Code Online (Sandbox Code Playgroud)

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