在 Django 视图中,我可以生成动态图像(PNG 格式的图形),并创建一个响应,该响应是我的图形的图像。我可以让它在浏览器中显示,但没有网页 - 它只是图像。
现在我想将此图像嵌入 HTML 模板中并渲染它。我怎样才能做到这一点?
(这是我的第一个 Django 项目。)
import matplotlib.pyplot as plt
import numpy as np
import io
# Initialize the matplotlib figure
f, ax = plt.subplots(figsize=(6, 15))
width = my_data['bar_length']
data_names = my_data['ObjectNames']
y_pos = np.arange(len(data_names))
norm = plt.Normalize(my_data['bar_length'].min(), my_data['bar_length'].max())
cmap = plt.get_cmap("RdYlGn")
# Create horizontal bars
plt.barh(y_pos, width, color=cmap(norm(my_data['bar_length'].values)))
# Create names on the y-axis
plt.yticks(y_pos, data_names)
FigureCanvasAgg(f)
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(f)
response = HttpResponse(buf.getvalue(), content_type='image/png')
# This works, but it generates just an image (no web page)
return response
# This ends up displaying the bytes of the image as text
#return render(request, 'my_app/graph.html', {'graph1': buf.getvalue()})
# This is what is in the graph.html template
# <div class="graph1">
# {{graph1 | safe}}
# </div>
已解决:我可以将图像作为 base64 编码字符串传递
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(f)
img_b64 = base64.b64encode(buf.getvalue()).decode()
return render(request, 'my_app/graph.html', {'graph1b64': img_b64})
# in graph.html
<div class="graph1">
<img src="data:image/png;base64, {{ graph1b64 }}" alt="graph1" />
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)