Displaying matplotlib plot in CGI with cStringIO

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 04:55:48

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/41500921/displaying-matplotlib-plot-in-cgi-with-cstringio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!