我想将matplotlib生成的图像存储在变量raw_data中,以将其用作内嵌图像。
import os
import sys
os.environ['MPLCONFIGDIR'] = '/tmp/'
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
print "Content-type: image/png\n"
plt.plot(range(10, 20))
raw_data = plt.show()
if raw_data:
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(raw_data))
print '<img src = "%s"/>' % uri
else:
print "No data"
#plt.savefig(sys.stdout, format='png')
这些功能都不适合我的用例:
答案 0 :(得分:29)
您是否尝试过cStringIO
或同等版本?
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import StringIO
import urllib, base64
plt.plot(range(10, 20))
fig = plt.gcf()
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
print "Content-type: image/png\n"
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
print '<img src = "%s"/>' % uri
答案 1 :(得分:12)
完整的python 3版本,将Paul's answer和metaperture's comment放在一起。
import matplotlib.pyplot as plt
import io
import urllib, base64
plt.plot(range(10))
fig = plt.gcf()
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
string = base64.b64encode(buf.read())
uri = 'data:image/png;base64,' + urllib.parse.quote(string)
html = '<img src = "%s"/>' % uri