小编典典

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

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

这是显示图像的地方

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

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


阅读 832

收藏
2020-04-05

共1个答案

小编典典

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

尝试使用Jinja渲染字节字符串之前,先将其解码为字符串。

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

Jinja在中渲染对象的字符串表示形式{{ }}。字节字符串的字符串表示形式包括,b''以将其与Unicode字符串区分开。因此,你必须解码才能直接显示其值。

2020-04-05