Skip to content

Instantly share code, notes, and snippets.

@dukenmarga
Last active April 24, 2020 23:23
Show Gist options
  • Save dukenmarga/1e3ad854b77c43d057aa to your computer and use it in GitHub Desktop.
Save dukenmarga/1e3ad854b77c43d057aa to your computer and use it in GitHub Desktop.
Serve dynamic image from Matplotlib using base64 encode string, from web framework CherryPy
# modified from https://gist.github.com/tebeka/5426211
# updated to work with Python 3
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
import numpy
import cherrypy
from io import BytesIO
import base64
class HelloWorld:
def index(self):
d = self.plot()
return ''' <img src="data:image/png;base64,%s" width="640" height="480" border="0" /> ''' %(d.decode('utf8'))
index.exposed = True
def plot(self):
image = BytesIO()
x = numpy.linspace(0, 10)
y = numpy.sin(x)
pyplot.plot(x, y)
pyplot.savefig(image, format='png')
return base64.encodestring(image.getvalue())
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())
@crabvk
Copy link

crabvk commented May 20, 2019

Using python 3.7, got error:

io.UnsupportedOperation: fileno
...
TypeError: string argument expected, got 'bytes'

fixed usign io.BytesIO instead of io.StringIO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment