Dynamically serving a matplotlib image to the web using python

Solution 1:

You should

  • first write to a cStringIO object
  • then write the HTTP header
  • then write the content of the cStringIO to stdout

Thus, if an error in savefig occured, you could still return something else, even another header. Some errors won't be recognized earlier, e.g., some problems with texts, too large image dimensions etc.

You need to tell savefig where to write the output. You can do:

format = "png"
sio = cStringIO.StringIO()
pyplot.savefig(sio, format=format)
print "Content-Type: image/%s\n" % format
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) # Needed this on windows, IIS
sys.stdout.write(sio.getvalue())

If you want to embed the image into HTML:

print "Content-Type: text/html\n"
print """<html><body>
...a bunch of text and html here...
<img src="data:image/png;base64,%s"/>
...more text and html...
</body></html>""" % sio.getvalue().encode("base64").strip()

Solution 2:

The above answers are a little outdated -- here's what works for me on Python3+ to get the raw bytes of the figure data.

import matplotlib.pyplot as plt
from io import BytesIO
fig = plt.figure()
plt.plot(range(10))
figdata = BytesIO()
fig.savefig(figdata, format='png')

As mentioned in other answers you now need to set a 'Content-Type' header to 'image/png' and write out the bytes.

Depending on what you are using as your webserver the code may vary. I use Tornado as my webserver and the code to do that is:

self.set_header('Content-Type', 'image/png')
self.write(figdata.getvalue())

Solution 3:

what works for me with python3 is:

buf = io.BytesIO()
plt.savefig(buf, format='png')
image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
buf.close()

Solution 4:

My first question is: Does the image change often? Do you want to keep the older ones? If it's a real-time thing, then your quest for optimisation is justified. Otherwise, the benefits from generating the image on the fly aren't that significant.

The code as it stands would require 2 requests:

  1. to get the html source you already have and
  2. to get the actual image

Probably the simplest way (keeping the web requests to a minimum) is @Alex L's comment, which would allow you to do it in a single request, by building a HTML with the image embedded in it.

Your code would be something like:

# Build your matplotlib image in a iostring here
# ......
#

# Initialise the base64 string
#
imgStr = "data:image/png;base64,"

imgStr += base64.b64encode(mybuffer)

print "Content-type: text/html\n"
print """<html><body>
# ...a bunch of text and html here...
    <img src="%s"></img>
#...more text and html...
    </body></html>
""" % imgStr

This code will probably not work out of the box, but shows the idea.

Note that this is a bad idea in general if your image doesn't really change too often or generating it takes a long time, because it will be generated every time.

Another way would be to generate the original html. Loading it will trigger a request for the "test.png". You can serve that separately, either via the buffer streaming solution you already mention, or from a static file.

Personally, I'd stick with a decoupled solution: generate the image by another process (making sure that there's always an image available) and use a very light thing to generate and serve the HTML.

HTH,