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?
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With