【发布时间】:2023-03-02 22:00:01
【问题描述】:
我需要在我的网页中显示图片。图像存储在 views.py 中的变量中。
大多数解决方案(例如下面的解决方案)使用 HttpResponse 输出图像,但我希望将图像嵌入到我的 html 模板中。
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
PS。我通过使用 matplotlib 创建图像来获取图像。所以我不能使用静态文件夹。下面给出的示例代码(信用:this)
import sys
from django.http import HttpResponse
import matplotlib as mpl
mpl.use('Agg') # Required to redirect locally
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
try:
# Python 2
import cStringIO
except ImportError:
# Python 3
import io
def get_image(request):
"""
This is an example script from the Matplotlib website, just to show
a working sample >>>
"""
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
"""
Now the redirect into the cStringIO or BytesIO object >>>
"""
if cStringIO in sys.modules:
f = cStringIO.StringIO() # Python 2
else:
f = io.BytesIO() # Python 3
plt.savefig(f, format="png", facecolor=(0.95,0.95,0.95))
plt.clf()
"""
Add the contents of the StringIO or BytesIO object to the response, matching the
mime type with the plot format (in this case, PNG) and return >>>
"""
return HttpResponse(f.getvalue(), content_type="image/png")
return HttpResponse(image_data, content_type="image/png")
【问题讨论】:
-
尚未找到解决方案。相反,我使用 将此页面(使用 HttpResponse 返回)嵌入到另一个 html 页面中
标签: django django-templates django-views