Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

embedding generated img inside django template

how would I embedded generated image inside django template?

something like

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")
like image 564
Sujit Avatar asked Jul 27 '10 20:07

Sujit


2 Answers

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}}"/>

Then in the view method:

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)

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.

like image 198
Paul Tomblin Avatar answered Nov 02 '22 15:11

Paul Tomblin


You can base64-encode the image data and use a data URI.

like image 29
James Bennett Avatar answered Nov 02 '22 15:11

James Bennett