Last active
April 24, 2020 23:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using python 3.7, got error:
fixed usign io.BytesIO instead of io.StringIO