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

2023-10-01前端开发问题
20

本文介绍了将 matplotlib png 转换为 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.

这篇关于将 matplotlib png 转换为 base64 以便在 html 模板中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui树状组件tree怎么默认勾选?
在layui树状组件tree中,勾选问题可以通过以下方法解决: 通过tree的oncheck事件来监听勾选操作,然后根据勾选状态进行相应的处理。例如: tree.on('check', function(obj) { // 获取勾选状态 var isChecked = obj.checked; // 获取当前节点数据 var data =...
2024-11-09 前端开发问题
372

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125