gpt4 book ai didi

Django 在模板中渲染动态图像

转载 作者:行者123 更新时间:2023-12-05 06:17:10 25 4
gpt4 key购买 nike

在 Django View 中,我可以生成一个动态图像(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>

关于Django 在模板中渲染动态图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61755900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com