【问题标题】:Django render dynamic image in templateDjango 在模板中渲染动态图像
【发布时间】:2020-05-13 03:31:19
【问题描述】:

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

【问题讨论】:

    标签: django python-3.x matplotlib


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 2018-06-23
      • 2017-04-26
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      相关资源
      最近更新 更多