如何在django模板中显示已保存的动态创建的图像?

时间:2017-06-23 20:24:47

标签: python html django image matplotlib

我在视图中创建了一个绘图,并将该绘图保存为templates文件夹中的png。但是当我尝试使用模板html文件中的<img>标记显示此保存的图像时,不会显示图像。 这是我的文件夹结构的图像: Folder Structure

这是我在视图中保存我的情节的方法:

def result(request):
    if request.POST and request.FILES:
        mycsv=pd.read_csv(request.FILES['csv_file'])
        c=mycsv.X
        #We divide by the class height(basically) so that Xi+1-Xi=1
        x = [d / 5 for d in c]
        n=len(x)
        b=mycsv.Y
        divi=np.sum(b)
        f = [e / divi for e in b] 
        #Thus sum(f)=1, makes calculation of mean simpler

        #PLOTTING BEGINS
        fig = plt.figure()
        ax = plt.subplot(111)
        ax.plot(x, f)
        plt.title('Pearson Type 1 ')
        ax.legend()
        #plt.show()
        fig.savefig('polls/templates/polls/plot.png')
        context = {'n':n,}
        return render(request, 'polls/result.html', context)
    else:
        return HttpResponse("Form Not Submitted")

我尝试获取图片的result.html文件是:

<h1>Graph with {{n}} points</h1>
<img src='./plot.png' />

我在我的localhost上运行此操作,是否存在权限问题?

我刚开始学习django并想测试这个东西。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

你的方法有很多不妥之处,但我会尝试给你一些关于如何继续的建议,尽管你可能想重新考虑它。

首先,将文件保存到模板目录不会使其可用于模板。 templates目录是一个特殊配置,允许您使用Django的模板加载器,它不会像您的图像一样加载静态文件。

您可以将图片保存为静态文件并使用{% static %}模板标记进行恢复,但是,这将是错误的方法,因为您的图片不是静态内容,它是动态创建的。

由于您在创建图像后没有使用图像中的数据,我的建议是使用TempFile将图像存储在临时文件中,或者(如果它是光的)在内存中使用StringIO,然后在上下文中将这些字节加载为base64

from StringIO import StringIO
import base64

img_in_memory = StringIO()
fig.savefig(img_in_memory, format="png") #dunno if your library can do that.
context['image'] = base64.b64encode(img_in_memory.getvalue())

然后,在您的模板中,您可以执行以下操作:

<img src="data:image/png;base64,{{image}}" />

答案 1 :(得分:0)

或者简单地将图像转换为字符串

with open(original_image_path, "rb") as img_file:
    base64_img = base64.b64encode(img_file.read()).decode('utf-8')
    mimetype = mimetypes.guess_type(original_image_path)[0]

一旦完成在 HTML 上呈现这个变量

<img src="data:{{ mimetype }};base64,{{ base64_img }}"/>

它将同时处理 jpeg 和 png。

相关问题