使用python动态将matplotlib图像提供给网络 [英] Dynamically serving a matplotlib image to the web using python

查看:147
本文介绍了使用python动态将matplotlib图像提供给网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经以类似的方式在此处提出了这个问题,但答案是在我的头上(我是python和Web开发的超级新手),所以我希望有一种更简单的方法,或者可以用不同的方式解释它.

This question has been asked in a similar way here but the answer was way over my head (I'm super new to python and web development) so I'm hoping there's a simpler way or it could be explained differently.

我正在尝试使用matplotlib生成图像并将其提供服务,而无需先将文件写入服务器.我的代码可能有点愚蠢,但它是这样的:

I'm trying to generate an image using matplotlib and serve it without first writing a file to the server. My code is probably kind of silly, but it goes like this:

import cgi
import matplotlib.pyplot as pyplot
import cStringIO #I think I will need this but not sure how to use

...a bunch of matplotlib stuff happens....
pyplot.savefig('test.png')

print "Content-type: text/html\n"
print """<html><body>
...a bunch of text and html here...
<img src="test.png"></img>
...more text and html...
</body></html>
"""

我认为我应该创建一个cstringIO对象,然后执行以下操作,而不是执行pyplot.savefig('test.png'):

I think that instead of doing pyplot.savefig('test.png'), I am supposed to create a cstringIO object and then do something like this:

mybuffer=cStringIO.StringIO()
pyplot.savefig(mybuffer, format="png")

但是我从那里迷路了.我看过的所有示例(例如 http://lost-theory.org/python/dynamicimg. html )涉及到类似

But I am pretty lost from there. All the examples I've seen (e.g. http://lost-theory.org/python/dynamicimg.html) involve doing something like

print "Content-type: image/png\n"

,我不知道如何将其与我已经输出的HTML集成在一起.

and I don't get how to integrate that with the HTML I'm already outputting.

推荐答案

您应该

  • 首先写入cStringIO对象
  • 然后编写HTTP标头
  • 然后将cStringIO的内容写入stdout

因此,如果在savefig中发生错误,您仍然可以返回其他内容,甚至是另一个标头.某些错误不会更早地识别出来,例如,文本问题,图像尺寸过大等.

Thus, if an error in savefig occured, you could still return something else, even another header. Some errors won't be recognized earlier, e.g., some problems with texts, too large image dimensions etc.

您需要告诉savefig将输出写入何处.您可以这样做:

You need to tell savefig where to write the output. You can do:

format = "png"
sio = cStringIO.StringIO()
pyplot.savefig(sio, format=format)
print "Content-Type: image/%s\n" % format
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) # Needed this on windows, IIS
sys.stdout.write(sio.getvalue())

如果要将图像嵌入到HTML中:

If you want to embed the image into HTML:

print "Content-Type: text/html\n"
print """<html><body>
...a bunch of text and html here...
<img src="data:image/png;base64,%s"/>
...more text and html...
</body></html>""" % sio.getvalue().encode("base64").strip()

这篇关于使用python动态将matplotlib图像提供给网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆