How do I get an image streamed from Cherrypy
into an HTML page?
I can get the image on its own, but I'm trying to get it into an HTML outline that I've defined:
class HelloWorld(object):
@cherrypy.expose
def index(self):
cherrypy.response.headers['Content-Type'] = "image/png"
plt.plot([1,2,3,4])
img = StringIO.StringIO()
plt.savefig(img,format='png')
imagedata = img.getvalue()
return """<html>
<head></head>
<body>
<p>Yo!</p>
<img src=imagedata />
</body>
</html>
"""
cherrypy.quickstart(HelloWorld())
The code above doesn't output anything - not even the Yo!
statement.
I figured out how to do it.
You have to:
StringIO
objectgetvalue()
base64.b64encode()
Place that base64 string inside an img
tag with the correct data:
arguments, like so:
class HelloWorld(object):
@cherrypy.expose
def index(self):
plt.plot([1,2,3,4])
img = StringIO.StringIO()
plt.savefig(img,format='png') # step 1.
imagedata = img.getvalue() # step 2.
encoded = base64.b64encode(imagedata) # step 3.
page = """<html>
<head></head>
<body>
<img src="data:image/png;base64,{0}" />
</body>
</html>
"""
return page.format(encoded) # step 4.
cherrypy.quickstart(HelloWorld())