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')
None 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 lineYou can store images in variables. And there are ways to output the image itself into the html, but they aren't that great.
Double-click on the variable image box. Browse to the folder where you want to look for images. Double-click on one of the images. Open the Variables tab and double-click on the variable that corresponds to the name of the image object you just created (such as Image1, Image2, Image3).
Saving an image in Python is just as simple. You simply call save() and pass in the name you want used to save your image. This method will save the image in the format identified by the extension on the filename you pass in.
An Image variable is a type of variable that represents an unknown image in your document. For example, if you want to ask a template user to insert a photograph you create an Image variable in your template to capture that specific item of data.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With