背景
您好,我正在尝试按照一个教程制作一个简单的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 %}
如果需要,我也可以提供 Controller 文件。谢谢你的帮助!

最佳答案

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

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

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

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

关于python - 将matplotlib png转换为base64以在html模板中查看,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31492525/

10-12 18:10
查看更多