在 Django 模板中嵌入生成的 img [英] embedding generated img inside django template
本文介绍了在 Django 模板中嵌入生成的 img的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 django 模板中嵌入生成的图像?
how would I embedded generated image inside django template?
类似的东西
return render_to_response('graph.html', { 'img': get_graph() })
我不想要这个 - 因为它只是发送图像
I don't want this - because it just send image
http.HttpResponse(get_graph(), mimetype="image/png")
推荐答案
我想将生成的 matplotlib 图像嵌入到 django 页面中,而无需两次访问 django 服务器(一次获取模板,一次生成图像).我将以下内容放在我的图像模板中
I wanted to embed a generated matplotlib image in a django page without making two trips to the django server (one to get the template, one to generate the image). I put the following in my template for the image
<img alt="embedded" src="data:image/png;base64,{{inline_png}}"/>
然后在视图方法中:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import cStringIO as StringIO
import base64
num_signed_off = random.randint(0, 10)
num_reviewed = random.randint(0, 50)
num_unreviewed = random.randint(0, 50)
fig = Figure()
ax = fig.add_subplot(111, aspect='equal', axis_bgcolor='b')
ax.pie([num_signed_off, num_reviewed, num_unreviewed],
labels=['Signed Off', 'Reviewed', 'Unreviewed'],
colors=['b', 'r', 'g'],
)
ax.set_title('My Overall Stats')
ax.set_axis_bgcolor('r')
canvas=FigureCanvas(fig)
outstr = StringIO.StringIO()
canvas.print_png(outstr)
ret['inline_png'] = base64.b64encode(outstr.getvalue())
outstr.close()
return render(request, "my_view.html", ret)
唯一的问题是它在 IE7 或 IE8 中不起作用 - 它适用于 IE9 和更新版本,想,当然还有所有基于标准的 Web 浏览器.
The only problem with this is that it doesn't work in IE7 or IE8 - it works with IE9 and newer, thought, and of course with all the standards-based web browsers.
这篇关于在 Django 模板中嵌入生成的 img的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文