这个问题已经以类似的方式被问到了,here,但答案超出了我的理解(我是python和web开发的新手),所以我希望有一种更简单的方法,或者可以用不同的方式解释它。
我正在尝试使用matplotlib生成一个图像,并在不先向服务器写入文件的情况下提供它。我的代码可能有点傻,但它是这样的:
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'):
mybuffer=cStringIO.StringIO()
pyplot.savefig(mybuffer, format="png")
但从那时起我就迷失了方向。我见过的所有示例(例如http://lost-theory.org/python/dynamicimg.html)都涉及到这样的操作
print "Content-type: image/png\n"
我不知道如何将它与我已经输出的HTML集成在一起。
发布于 2015-06-01 20:56:55
上面的答案有点过时--下面是我在Python3+上获取图形数据的原始字节的方法。
import matplotlib.pyplot as plt
from io import BytesIO
fig = plt.figure()
plt.plot(range(10))
figdata = BytesIO()
fig.savefig(figdata, format='png')
正如在其他答案中提到的,您现在需要将“Content-Type”标头设置为“image/png”,并写出字节。
根据您使用的may服务器,代码可能会有所不同。我使用Tornado作为我的the服务器,它的代码是:
self.set_header('Content-Type', 'image/png')
self.write(figdata.getvalue())
发布于 2015-09-11 02:40:40
对我来说,python3的工作原理是:
buf = io.BytesIO()
plt.savefig(buf, format='png')
image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
buf.close()
发布于 2013-02-12 10:46:34
除非我严重误解了您的问题,否则您所需要做的就是cd到镜像的位置并运行: python -m SimpleHTTPServer 8000 &
然后打开浏览器,在地址栏中键入http://localhost:8000/
。
https://stackoverflow.com/questions/14824522
复制相似问题