wiki:FAQ_MatlabPlots

Version 1 (modified by dkearney, 18 years ago) (diff)

--

How do I display Matlab plots as a result?

The first step is to save the graph as a png image. The Matlab / Octave example below shows how to do this using the print function and the -dpng flag:

%% test.m

% A function of two variables, described in Matlab help.
% The output is 20x20 matrix of Z values

isOctave= exist('OCTAVE_VERSION');
fname='tst';
fff=peaks(20);  
mesh(fff);                   % Test figure shown for adjustment

% Flush pending graphics events
drawnow;

% this command saves the graph as a png file
eval(sprintf('print -dpng %s.png',fname));

Once you have a png file, you will need to convert this byte stream to base64 encoded data. If the matlab or octave script has Rappture library calls embedded inside of it, you can make a system call to the mimencode function. Check out Pics In XML for more information on using mimencode to put image data into rappture xml files. The system call would look similar to this:

% this command turns it into a mime file
if isOctave
    convertCmd=sprintf('mimencode %s.png > %s.mime',fname,fname);
    eval(system(convertCmd));
else
    convertCmd=sprintf('! mimencode %s.png > %s.mime',fname,fname);
    eval(convertCmd);
end

After conversion, read in the newly formed *.mime file and place the contents into the xml function using the rpLibPutString function. The base64 encoded data will need to be placed in the 'output' section of the xml file. Check out these pages for more information on placing base64 encoded data into image and structure nodes.

If a wrapper script calls the matlab script, the base64 encoding can be done inside the wrapper script. Tcl and Python have special modules to deal with image conversions.

Here's an example of converting a tiff image to base64 encoding in Python:

#! /bin/sh
#
""":"
exec /apps/rappture/bin/python $0 ${1+"$@"}
"""

import base64, Rappture
from PIL import Image
xmlfile = "driverNNNN.xml"
lib = Rappture.library(xmlfile)
if isinstance(lib,Rappture.library):
    im_tiff=Image.open("image.tiff")
    if im_tiff:
        im_tiff.save("image.jpg")
        im_jpeg=open("image.jpg",'r')

        # generate MIME data from image
        jpgMIMEdata = base64.encodestring(im_jpeg.read())
    
        # write the images to the xml library
        graphName = "image.jpg"
        path = 'output.image(%s)' % graphName
        lib.put(path + '.about.label', graphName)
        lib.put(path + '.current', jpgMIMEdata)

print lib.xml()

Back to Frequently Asked Questions