Exporting Figures and Images

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The reference material consulted while preparing these pages is listed in the section bibliography.

Written against MATLAB R2026b. Saving a chart needs a figure, so the exportgraphics, copygraphics, saveas, print and savefig code on this page is not run here and was checked against the R2026b documentation. The image-file functions imwrite, imread and imfinfo do not need a display, and they were run in GNU Octave 11.3.0 on a small heatflow image; that output is labelled Octave 11.3.0 output and MATLAB’s imfinfo returns a longer structure (see below). The figures on this page are original drawings, not exports from MATLAB.

The charts of 2-D Plotting and 3-D Plotting and Surfaces live in a figure window. To put one in a report, a web page or a slide it has to be saved as a file or copied to the clipboard, and the data of an image has to be read from and written to a file with the image functions.

Terminology

  • A raster (or image) file stores a grid of pixels (PNG, JPEG, TIFF, GIF). It looks sharp at the size it was made for and blurs when scaled.

  • A vector graphics file stores shapes and text (SVG, PDF, EPS, EMF). It scales to any size.

  • Resolution is the number of dots per inch (DPI) of a raster export.

  • A FIG-file is MATLAB’s own format for saving a whole figure so that MATLAB can reopen it.

  • An indexed image is a matrix of indices plus a colormap; a grayscale image is a matrix of intensities; a truecolor (RGB) image is an m-by-n-by-3 array.

Which function to use

The documentation compares the ways of exporting. In short:

Function Use it to

exportgraphics(obj,filename)

Save a chart for a document, an email or a presentation, tightly cropped. This is the function to use by default.

copygraphics(obj)

Copy a chart to the system clipboard to paste it into another application.

print(fig,filename,"-dpng")

Save a chart within a full-size page, for instance a full-page PDF. The older route.

saveas(fig,filename)

Save a figure by file extension. The older route, simpler and less controllable than exportgraphics.

getframe and imwrite

Capture the pixels of a figure and write them with image options that the other functions do not support, such as BMP.

exportapp(fig,filename)

Save an app window that contains interface components.

savefig(fig,filename)

Save a figure as a FIG-file to reopen later in MATLAB (it is not an image).

exportgraphics

exportgraphics(obj,filename) saves the contents of a figure, any type of axes, a standalone chart, a tiled chart layout or a container such as a panel to a file. The format comes from the extension of filename, and the result is cropped to a thin margin around the content. It was introduced in R2020a. It does not capture interface components such as buttons and sliders.

Name-value argument Meaning

Resolution=300

DPI of image output; the default is 150. It has no effect on HTML output or on vector content.

ContentType="vector"

For PDF, EPS and EMF (and SVG): store shapes and text so that the file scales; for PDF the fonts are embedded. "image" stores the content as images, and "auto" (default) lets MATLAB decide. "vector" is not supported for JPEG, TIFF, PNG, GIF or HTML files, and some charts can show stray lines or artifacts when exported as vector content.

BackgroundColor="none"

Colour of the margin: "current" (default), "none" for a transparent background (vector content only), an RGB triplet, a hexadecimal code or a colour name. Without an explicit colour the background follows the theme of the figure (since R2025a: white for light, near black for dark).

Append=true

Add a page to an existing PDF or a frame to an animated GIF. PDF and GIF only.

Colorspace="gray"

"rgb" (default), "gray", or "cmyk" (EPS only).

Width, Height, Padding, Units

Size and padding of the output (since R2025a). The default units are pixels for images and points for vector files.

The supported formats are JPEG, PNG, TIFF and GIF for images, and SVG (since R2025a), PDF, EPS and EMF (Windows only) for vector graphics. Since R2026a exportgraphics can also write an HTML file that contains an interactive web canvas.

t  = (0:30)';
S1 = 20 + 6.0*(1 - exp(-t/8));
S2 = 20 + 4.0*(1 - exp(-t/11));

plot(t, S1, t, S2)
xlabel("Time (min)")
ylabel("Temperature (\circ C)")
legend("S1", "S2", Location="southeast")
ax = gca;

exportgraphics(ax, "sensors.png", Resolution=300)                    % raster, 300 DPI
exportgraphics(ax, "sensors.pdf", ContentType="vector")              % scalable PDF with embedded fonts
exportgraphics(ax, "sensors.svg", ContentType="vector")              % SVG (R2025a or later)
exportgraphics(ax, "sensors_clear.pdf", BackgroundColor="none", ContentType="vector")   % transparent margin

Not run here. The calls write four files in the current folder from the same axes: a 300-DPI PNG, a vector PDF, a vector SVG and a vector PDF with a transparent margin. BackgroundColor="none" gives a transparent margin only for vector content; with ContentType="image" the margin is white (or near black for a dark theme). The drawing in the 2-D plotting page that shows the sensor curves is the picture these calls would produce, drawn by hand from the same data.

Exporting a layout or a figure saves everything in it, and exporting one axes of a layout saves that tile only:

tl  = tiledlayout(2, 1);
ax1 = nexttile;  plot(ax1, t, S1)
ax2 = nexttile;  plot(ax2, t, S2)

exportgraphics(tl,  "both.pdf")                    % the whole layout
exportgraphics(ax1, "tile1.pdf", Append=false)     % one tile, overwriting an existing file
exportgraphics(ax2, "both.pdf", Append=true)       % add a page to a PDF

Not run here. The first call writes a PDF with both tiles, the second a PDF with the first tile only, and the third adds the second tile as another page of both.pdf.

An animated GIF

Append=true with a GIF file adds one frame per call; the charts must have the same axes limits or the frames jump (fix them with axis manual or xlim and ylim). For more elaborate animations the documentation points to imwrite.

h = plot(0, 20, "o");
xlim([0 30]), ylim([19 27])
for k = 0:30
    h.XData = k;
    h.YData = 20 + 6.0*(1 - exp(-k/8));
    exportgraphics(gca, "sensor.gif", Append=true)
end

Not run here. The output is a GIF in which a marker moves along the S1 curve in 31 frames.

copygraphics

copygraphics(obj) places the content on the clipboard (R2020a), accepts the same kinds of objects as exportgraphics, and takes ContentType, Resolution and BackgroundColor, plus Width, Height, Padding and Units since R2025a. The menu route is Copy Figure from the figure toolstrip, whose settings are in the MATLAB settings window.

copygraphics(gcf, Resolution=300)             % image for a slide or a document
copygraphics(gca, ContentType="vector")       % vector content where the target application accepts it

Not run here. The clipboard then holds the chart, ready to paste.

saveas and print, the older routes

  • saveas(fig,"name.png") infers the format from the extension. With a third argument it uses that format, even when the extension says otherwise: saveas(gcf,"Barchart","epsc") writes a colour EPS file named Barchart.eps. Without an extension it saves a FIG-file. If you pass an axes instead of a figure, saveas saves the figure that contains it.

  • print(fig,"name","-dpng","-r300") saves with a device flag ("-dpng", "-djpeg", "-dtiff", "-dpdf", "-dsvg", "-deps", "-depsc") and a resolution flag. "-vector" or "-image" selects the content type, "-bestfit" and "-fillpage" scale a PDF to the page, and a printer name sends the figure to a printer. print keeps the whole figure, including the white space around the charts.

  • Since R2025a print and saveas no longer capture interface components or containers such as panels and tabs, and no longer write BMP, HDF, PBM, PCX, PGM, PPM or full-page PostScript (.ps) files. For a BMP or a similar format use getframe with imwrite; for an app window use exportapp. The functions hgexport and printopt were removed in R2025a too.

plot(t, S1)
F = getframe(gcf);                 % a structure with the field cdata, an m-by-n-by-3 uint8 array
imwrite(F.cdata, "sensors.bmp")
print(gcf, "sensors_full", "-dpdf", "-bestfit")

Not run here. The first two lines capture the figure’s pixels and write a BMP file. The print call writes a PDF that fills the page while keeping the aspect ratio.

Saving a figure to reopen: savefig and openfig

savefig(fig,"name.fig") saves the figure with all its objects in a compact FIG-file (MAT-file based; the file opens in R2014b and later, and since R2024b not in R2014a or earlier). savefig(fig_array,"name.fig") saves several figures in one file, and a third argument chooses the MAT-file version, "-v7.3", "-v7" or "-v6" (R2024b). openfig("name.fig") recreates the figure. open("name.fig") does the same.

fig = figure;
plot(t, S1)
savefig(fig, "sensors.fig")
close(fig)

fig2 = openfig("sensors.fig");     % a new figure with the same line

Not run here. The saved figure has the same data and appearance as the original.

A FIG-file is not only data. The documentation warns that openfig can run code that the file contains while it loads the graphics objects, so do not open FIG-files from sources you do not trust. A FIG-file cannot be read by another application, so save the data with save or writematrix as well when the data matters (see Workspace Variables and MAT-Files).

Images in base MATLAB

An image is an array. A grayscale or indexed image is an m-by-n matrix, a truecolor image is m-by-n-by-3. The base MATLAB functions below read, write, describe and display image files. Functions of the Image Processing Toolbox (imshow, imresize, rgb2gray, imadjust, imfilter and the rest) are out of scope here and are listed on Toolboxes and Add-On Products.

Function What it does

A = imread(filename)

Reads an image file; the format is inferred from the contents. A multi-image file returns the first image unless an index is given. [A,map] = imread(___) also returns the colormap of an indexed image, rescaled to the range 0 to 1.

imwrite(A,filename)

Writes A. A uint8 array becomes 8-bit values; a uint16 array 16-bit values for JPEG, PNG and TIFF; a double or single grayscale or RGB array is assumed to be in the range 0 to 1 and scaled by 255; a logical array a binary image. imwrite(A,map,filename) writes an indexed image.

info = imfinfo(filename)

A structure with the format, size, bit depth, colour type and other details of the file.

image©

Displays C as an image. For an indexed image the values are indices into the colormap, and without scaling.

imagesc©

Displays a matrix using the full range of the colormap, so it is the quick way to see a matrix of data.

The origin of an image matrix is its top-left corner: row 1 is drawn at the top, and the y-axis of image and imagesc points down. A grid built with meshgrid has y = 0 in its first row, so imagesc(T) draws the bottom edge of the heatflow plate at the top unless the axes direction is reversed.

The heatflow field as a 21-by-41 grayscale image, written to a PNG file, described, read back and written again as an indexed image. The code uses only functions that exist in both MATLAB and Octave; it was run in Octave 11.3.0, and the files are deleted at the end:

Lx = 1; Ly = 0.5;
[X, Y] = meshgrid(linspace(0, Lx, 41), linspace(0, Ly, 21));
T = 100*sin(pi*X/Lx).*sinh(pi*Y/Lx)/sinh(pi*Ly/Lx);
G = uint8(round(255*T/100));          % grayscale image, 21 rows by 41 columns
fprintf("class %s, size %s, max %d\n", class(G), mat2str(size(G)), max(G(:)));
imwrite(G, "field.png");
info = imfinfo("field.png");
fprintf("format %s, width %d, height %d, bit depth %d, color type %s\n", info.Format, info.Width, info.Height, info.BitDepth, info.ColorType);
B = imread("field.png");
fprintf("read back: class %s, size %s, identical: %d\n", class(B), mat2str(size(B)), isequal(B, G));
map = hot(256);
imwrite(G, map, "field_indexed.png");
[A, m] = imread("field_indexed.png");
fprintf("indexed: class %s, size(A) %s, colormap rows %d\n", class(A), mat2str(size(A)), size(m,1));
F = flipud(G);                         % imagesc/image draw row 1 at the top
fprintf("G(1,21) = %d (y = 0 edge), F(1,21) = %d (y = 0.5 edge)\n", G(1,21), F(1,21));
delete("field.png"); delete("field_indexed.png");

Octave 11.3.0 output:

class uint8, size [21 41], max 255
format PNG, width 41, height 21, bit depth 8, color type grayscale
read back: class uint8, size [21 41], identical: 1
indexed: class uint8, size(A) [21 41], colormap rows 256
G(1,21) = 0 (y = 0 edge), F(1,21) = 255 (y = 0.5 edge)

The round trip is exact for uint8 data in a PNG file (the lossless format), the file records width 41 and height 21, so the size is columns by rows in imfinfo but rows by columns in the matrix, and the indexed file keeps a 256-row colormap. flipud turns the grid so that the hot edge appears at the top of a displayed image, as in a plot. A JPEG file would change the values slightly because the format is lossy. In MATLAB imfinfo returns more fields (file name, modification date, file size and so on); the five used here exist in both.

imagesc(flipud(T))                 % in MATLAB: display with the hot edge at the top
colormap("hot")
colorbar
axis image                         % square pixels
title("Steady temperature (\circ C)")
exportgraphics(gca, "field.png", Resolution=200)

Not run here. The chart shows the temperature field as 41 by 21 coloured cells, hot at the top middle, with a colorbar from 0 to 100; the last call saves it as a 200-DPI PNG file.

Common errors and pitfalls

The messages were not run here; the causes are documented behaviour.

  • Saving before drawing. exportgraphics(gca,...) after close all creates an empty figure and saves it. Draw first and keep the handle: ax = gca.

  • Extension and format disagree. saveas(gcf,"x.png","epsc") writes EPS content into a file called x.png. Make the extension match the format, or use exportgraphics, which uses the extension.

  • ContentType="vector" with a raster extension. It is not supported for JPEG, PNG, TIFF, GIF or HTML files.

  • Vector artifacts. Some charts, such as surfaces with many patches, can show stray lines in vector output; export them with ContentType="image" at a high resolution instead.

  • A double image outside 0 to 1. imwrite of a double matrix assumes the range 0 to 1 and scales it by 255, so values such as 0 to 100 saturate to white. Rescale the data or convert to uint8 first, as the example does.

  • Lossy formats. JPEG compression changes pixel values; use PNG or TIFF to keep data exactly.

  • Missing support after R2025a. Code that calls print or saveas for a BMP, PBM, PCX, PGM, PPM, HDF or PS file errors. Use getframe with imwrite.

  • Reopening untrusted FIG-files. openfig can execute code in the file.

  • Row and column order of an image. size returns rows then columns; imfinfo reports Width then Height; and image draws row 1 at the top.

Where older books differ

  • Books before R2020a use saveas, print -dpng -r300 and hgexport. The hgexport function was removed in R2025a; exportgraphics and copygraphics (R2020a) are the replacements, and SVG output through exportgraphics arrived in R2025a.

  • The print options -dmeta, -dbitmap and -clipboard are still in old code; copygraphics is the cross-platform way to copy.

  • Old books call imread and imwrite with the format as a second argument (imread("a.jpg","jpg")), and use imshow, which needs the Image Processing Toolbox. In base MATLAB use image and imagesc.

  • The FIG-file format has changed several times; files saved by current releases do not open in R2014a and earlier (R2024b release note in the savefig page).