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

2022-01-21 00:00:00 python matplotlib flask base64 html

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

Hello, I am trying to make a simple web app, following a tutorial, that calculates a dampened vibration equation and returns a png of the result to the html page after it has been converted to a Base64 string.

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

The app functions normally except that when the result is calculated, a broken image icon is returned, likely because the Base64 string is not valid.

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

I have converted another png image to a Base64 string using an online converter and used <img src="data:image/png;base64, BASE64_STRING"/> to display the image successfully. I believe the template is appropriately formatted. I have also read other SO answers here and here and tried implementing those without success.

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

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

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

If needed, I can provide the controller file as well. Thanks for any help!

推荐答案

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

The beginning of the data in the template gives a clue to what's happening. &#39; is the HTML entity for a single quote '. Combined with the preceding b, b', it looks like the representation of a byte string, rather than the contents of the string.

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

Decode the byte string to a string before trying to render them with Jinja.

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

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

Jinja renders the string representation of objects in {{ }}. The string representation of a byte string includes the b'' to distinguish it from a Unicode string. So you have to decode in order to display their value directly.

相关文章