Search code examples
python-2.7cherrypy

Cherrypy image in HTML


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.


Solution

  • I figured out how to do it.

    You have to:

    1. Save the figure into a StringIO object
    2. Get the content of the object with getvalue()
    3. Encode the content to base64 with base64.b64encode()
    4. 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())