1

Trying to return a simple plot (saved in StringIO) to web browser. After hours of reading, finally getting close, maybe.

import cgi
import cStringIO
import matplotlib.pyplot as plt
import numpy as np


def doit():

    x = np.linspace(-2,2,100)
    y = np.sin(x)

    format = "png"
    ggg = cStringIO.StringIO()

    plt.plot(x, y)
    plt.savefig(ggg, format=format)

    data_uri = ggg.read().encode('base64').replace('\n', '')
    img_tag = '<img src="data:image/png;base64,{0}" alt="thisistheplot"/>'.format(data_uri)

    print("Content-type: text/html\n")
    print("<title>Try Ageen</title>")
    print("<h1>Hi</h1>")
    print(img_tag)

doit()

It's returning a broken image icon. I've looked already read this: Dynamically serving a matplotlib image to the web using python, among others...

Community
  • 1
  • 1
peer
  • 162
  • 5
  • 17

1 Answers1

0

Actually, just figured it out. Will leave posted, as I haven't seen this approach being taken and hope it can help:

#!/usr/bin/env python
import cgi
import cStringIO
import matplotlib.pyplot as plt
import numpy as np


def doit():

    x = np.linspace(-2,2,100)
    y = np.sin(x)
    format = "png"
    sio = cStringIO.StringIO()
    plt.plot(x, y)
    plt.savefig(sio, format=format)

    data_uri = sio.getvalue().encode('base64').replace('\n', '')
    img_tag = '<img src="data:image/png;base64,{0}" alt="sucka" />'.format(data_uri)

    print("Content-type: text/html\n")
    print("<title>Try Ageen</title>")
    print("<h1>Hi</h1>")
    print(img_tag)

doit()

The goal is to have a client input a trigonometric function and have it returned on a subsequent page. Still any comments to help this code perform/look better are welcomed.

peer
  • 162
  • 5
  • 17