开发者

How to store an image in a variable

I would like to store the image generated by matplotlib in a variable raw_data to use it as inline image.

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

Non开发者_运维问答e of the functions suit my use case:

  • plt.savefig(sys.stdout, format='png') - Writes it to stdout. This does help.. as I have to embed the image in a html file.
  • plt.show() / plt.draw() does nothing when executed from command line


Have you tried cStringIO or an equivalent?

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


Complete python 3 version, putting together Paul's answer and 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜