[ACCEPTED]-Returning Matplotlib image as string-matplotlib
Django's HttpResponse
object supports file-like API 2 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 1 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
0
There is a recipe in the Matplotlib Cookbook that does exactly 13 this. At its core, it looks like:
def simple(request):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig=Figure()
ax=fig.add_subplot(111)
ax.plot(range(10), range(10), '-')
canvas=FigureCanvas(fig)
response=django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
Put that 12 in your views file, point your URL to it, and 11 you're off and running.
Edit: As noted, this 10 is a simplified version of a recipe in the 9 cookbook. However, it looks like there 8 is a difference between calling print_png
and savefig
, at 7 least in the initial test that I did. Calling 6 fig.savefig(response, format='png')
gave an image with that was larger and 5 had a white background, while the original 4 canvas.print_png(response)
gave a slightly smaller image with a grey 3 background. So, I would replace the last 2 few lines above with:
canvas=FigureCanvas(fig)
response=django.http.HttpResponse(content_type='image/png')
fig.savefig(response, format='png')
return response
You still need to have 1 the canvas instantiated, though.
Employ ducktyping and pass a object of your 3 own, in disguise of file object
class MyFile(object):
def __init__(self):
self._data = ""
def write(self, data):
self._data += data
myfile = MyFile()
fig.savefig(myfile)
print myfile._data
you can use 2 myfile = StringIO.StringIO() instead in 1 real code and return data in reponse e.g.
output = StringIO.StringIO()
fig.savefig(output)
contents = output.getvalue()
return HttpResponse(contents , mimetype="image/png")
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.