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

查看:31
本文介绍了使用 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
"
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
"

我不知道如何将它与我已经输出的 HTML 集成.

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

推荐答案

你应该

  • 首先写入一个 cStringIO 对象
  • 然后写入 HTTP 标头
  • 然后将 cStringIO 的内容写入标准输出

因此,如果 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
" % 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
"
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天全站免登陆