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

时间:2015-07-18 15:09:02

标签: python html matplotlib flask base64

背景

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

问题

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

疑难解答

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

相关代码

以下是返回图片字符串的位置

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 %}

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

2 个答案:

答案 0 :(得分:16)

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

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

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

Jinja在{{ }}中呈现对象的字符串表示。字节字符串的字符串表示形式包括b'',以区别于Unicode字符串。所以你必须解码才能直接显示它们的值。

答案 1 :(得分:-3)

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