背景
你好,我正在尝试制作一个简单的网络应用程序,按照教程计算阻尼振动方程,并将结果的 png 返回到 html 页面,然后将其转换为 Base64 字符串。
Problem
该应用程序运行正常,只是在计算结果时返回损坏的图像图标,可能是因为 Base64 字符串无效。
故障排除
我已经使用在线转换器将另一个 png 图像转换为 Base64 字符串并使用<img src="data:image/png;base64, BASE64_STRING"/>
即可成功显示图像。我相信模板的格式正确。我还阅读了其他答案here https://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask and here https://stackoverflow.com/questions/28091129/what-is-the-difference-among-idioms-for-serving-a-matplotlib-image-with-flask并尝试实施这些但没有成功。
相关代码
这是返回图像字符串的地方
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 %}
如果需要,我也可以提供控制器文件。谢谢你的帮助!