Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an image in a variable

Tags:

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 line
like image 301
Ramya Avatar asked Mar 15 '11 16:03

Ramya


People also ask

Can we store image in variable?

You can store images in variables. And there are ways to output the image itself into the html, but they aren't that great.

How do you add an image to a variable?

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

How do I save an image to a variable in Python?

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.

How can an image be used as a variable?

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.


1 Answers

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 
like image 65
Paul Avatar answered Sep 20 '22 04:09

Paul