Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Matplotlib image as string

I am using matplotlib in a django app and would like to directly return the rendered image. So far I can go plt.savefig(...), then return the location of the image.

What I want to do is:

return HttpResponse(plt.renderfig(...), mimetype="image/png")

Any ideas?

like image 557
DarwinSurvivor Avatar asked Jul 10 '09 10:07

DarwinSurvivor


Video Answer


2 Answers

Django's HttpResponse object supports file-like API and you can pass a file-object to savefig.

response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response

Hence, you can return the image directly in the HttpResponse.

like image 54
wierob Avatar answered Sep 27 '22 17:09

wierob


what about cStringIO?

import pylab
import cStringIO
pylab.plot([3,7,2,1])
output = cStringIO.StringIO()
pylab.savefig('test.png', dpi=75)
pylab.savefig(output, dpi=75)
print output.getvalue() == open('test.png', 'rb').read() # True
like image 34
sunqiang Avatar answered Sep 27 '22 15:09

sunqiang