【问题标题】:Displaying matplotlib plot in CGI with cStringIO使用 cStringIO 在 CGI 中显示 matplotlib 图
【发布时间】:2017-01-06 07:23:46
【问题描述】:

试图将一个简单的图(保存在 StringIO 中)返回到 Web 浏览器。经过几个小时的阅读,也许终于接近了。

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()

它返回一个损坏的图像图标。我已经看过了:Dynamically serving a matplotlib image to the web using python,等等……

【问题讨论】:

    标签: python string image matplotlib cgi


    【解决方案1】:

    其实,刚刚想通了。将留下发布,因为我还没有看到这种方法被采用,并希望它可以帮助:

    #!/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()
    

    目标是让客户输入三角函数并在后续页面上返回。仍然欢迎任何有助于此代码执行/看起来更好的 cmets。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 2019-09-19
      • 1970-01-01
      • 2016-06-07
      • 2017-12-25
      • 2017-07-10
      • 1970-01-01
      相关资源
      最近更新 更多