Django在模板中渲染动态图像

时间:2020-05-12 15:41:44

标签: django python-3.x matplotlib

在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>

1 个答案:

答案 0 :(得分:0)

已解决:我可以将图像作为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>