File Exchange

image thumbnail

ScreenCapture - get a screen-capture of a figure frame or component

version (41.9 KB) by Yair Altman
ScreenCapture gets a screen-capture of any Matlab GUI handle, or specified screen area rectangle


Updated 16 May 2016

View Version History

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

ScreenCapture gets a screen-capture of any Matlab GUI handle (including desktop, figure, axes, image, or uicontrol), or a specified area rectangle located relative to the specified handle.

Screen area capture is possible by specifying the root (desktop) handle (=0).

The output can be either to an image file or to a Matlab matrix (useful for displaying via imshow() or for further processing), or to the system clipboard.

This utility also enables adding a toolbar button for easy interactive screen-capture.

imageData = screencapture(handle, position, target, 'PropName',PropValue, ...)

Input Parameters:
handle - optional handle to be used for screen-capture origin.
If empty/unsupplied then current figure (gcf) will be used.
position - optional position array in pixels: [x,y,width,height].
If empty or non-specified then the handle's position vector will be used.
If both handle and position are empty or non-specified then the position
will be retrieved via interactive mouse-selection.
If handle is an image, then position is in data (not pixel) units, so the
captured region remains the same after figure/axes resize (like imcrop)
target - optional filename for storing the screen-capture, or the 'clipboard'/'printer' string.
If empty or non-specified then no output to file will be done.
The file format will be determined from its extension (JPG/PNG/...).
Supported formats are those supported by the imwrite function.
If neither target nor imageData were specified, the user will be asked to
interactively specify the output file.
'PropName',PropValue -
optional list of property pairs
e.g., screencapture('target','sc.png','pos',[10,20,30,40],'handle',gca)
PropNames may be abbreviated and are case-insensitive.
PropNames may also be given in whichever order.
Supported PropNames are:
- 'handle' (default: gcf handle)
- 'position' (default: gcf position array)
- 'target' (default: '')
- 'toolbar' (figure handle; default: gcf)
this adds a screen-capture button to the figure's toolbar
If this parameter is specified, then no screen-capture
will take place and the returned imageData will be [].

Output parameters:
imageData - image data in a format acceptable by the imshow function.
If neither filename nor imageData were specified,
the user will be asked to interactively specify the output file.

imageData = screencapture; % interactively select screen-capture rectangle
imageData = screencapture(hListbox); % capture image of a uicontrol
imageData = screencapture(0, [20,30,40,50]); % select a small desktop region
imageData = screencapture(gcf,[20,30,40,50]); % select a small figure region
imageData = screencapture(gca,[10,20,30,40]); % select a small axes region
imshow(imageData); % display the captured image in a matlab figure
imwrite(imageData,'myImage.png'); % save the captured image to file
screencapture(gcf,[],'myFigure.jpg'); % capture the entire figure into file
screencapture(gcf,[],'clipboard'); % capture the entire figure into clipboard
screencapture(gcf,[],'printer'); % print the entire figure
screencapture('handle',gcf, 'target','myFigure.jpg'); % same as previous, save to file
screencapture('handle',gcf, 'target','clipboard'); % same as previous, copy to system clipboard
screencapture('handle',gcf, 'target','printer'); % same as previous, send to printer
screencapture('toolbar',gcf); % adds a screen-capture button to gcf's toolbar
screencapture('toolbar',[], 'target','sc.bmp'); % same with default output filename

Technical description:

Bugs and suggestions:
Please send to Yair Altman (altmany at gmail dot com)

Cite As

Yair Altman (2021). ScreenCapture - get a screen-capture of a figure frame or component (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (77)

Matthew Schroeder

Nick Hunter

Well written code, thank you :3 However, I have just found a bug. It is impossible to capture the entire screen using

img = screencapture(0, 'Position',get(0,'ScreenSize'));

as 2 bottom rows of pixels are going to be lost.

The quick fix is

img = screencapture(0, 'Position',get(0,'ScreenSize')-[0,2,0,0]);

Nick Hunter

Beautiful :3

weicheng Xu

Lukas Längle

@Arthur & @Adam - I had the same Issue, I quickly added the screenScale - Parameter in line 472 to 475

screenScale = 1.25; %added

javaX = screenScale*(desktopPos(1) + paramsStruct.position(1) + deltaX + dX);
javaY = screenScale*(screenSize(4) - desktopPos(2) - paramsStruct.position(2) - paramsStruct.position(4) + deltaY + dY);
width = screenScale*paramsStruct.position(3) + dW;
height = screenScale*paramsStruct.position(4) + dH;

Yair Altman

@Arthur & @Adam - it works ok for me on my Win10 R2019bPR using the following test-case: f=uifigure; p=uipanel(f,'Position',[5,5,550,410]); a=axes(p); surf(a,peaks); d=screencapture(f); figure; imshow(d)
In the displayed popup figure I clearly see the surf(peaks) axes within the rectangular border, in both 100% and 125% settings, without any visible cropping to the image.
If you have a test-case that doesn't work, send it to me.

Arthur Roué

Hello Yair Altman,
I needed a solution to take screenshots of uifigures (appdesigner) and your function worked just fine. However, I noticed the same problem than @Adam Filion bellow : when the default scale ratio is not 100% (Control Panel -> Appearance -> Display) but 125% or more, screenshot is badly taken. Is there anyway to take into account screensize scale ratio in your tool ?
Thanks !

Yalei SONG

Andrew Lee




Andra Arnicane

Great tool, Yair, thanks a lot!
Has anyone tried to use it with Psychtoolbox (running in Matlab)? I'd like to take screenshots of images presented via Psychtoolbox. When Psychtoolbox takes over the screen, I only see the image I am presenting. When I take a screencapture during this time, however, teh background screen of Matlab is captured, and not the foreground image as i want.
Does anyone have a suggestion how to capture the foreground window?
Thanks in advance,

manuel domhoff

Anne Urai


Yunhui Zhou

Azura Hashim

Hi, if there is a browser pop up on the screen, e.g. session about to expire, the code waits. Is there a way around this? Thanks.

Rodrigo San Martín


How to get a better resolution capture?
With Matlab OCR I must get numbers, but 5 is confused with 6, and 3 is confused with 8.




Ivan Shorokhov

Hello Yair Altman,

I want use your code for OCR of online text, I have tried to use
imageData = screencapture;
to interactively select screen-capture rectangle outside the matlab, but it didn't work. Then I have tried the following:
imageData = screencapture(gca);
no much luck ether.

Could you tell me please how I can interactively select screen-capture rectangle outside the matlab?

Adam Filion

Hi Yair, great tool.

I ran into a problem when the Windows 7 feature in Control Panel -> Appearance -> Display was at the default 125%. This tool is supposed to make certain things on screen appear bigger to make them easier to see, however it looks like the underlying java robot does not take this into account. screencapture doesn't work right at the default 125%, capturing only part of the figure window plus some area outside it, but works perfectly if I change it to 100%.

Might want to add a comment in the file warning about this (or if there's a way to programatically detect it and warn, even better).

Dwight Bartholomew

I tried running 2 instances of a program that uses this utility. Occasionally, 1 of the instances produces an error where it can't access the System Clipboard; I presume because the other instance has control of the Clipboard. Can you think of a way to have the software wait until the Clipboard is free (perhaps with a timeout) before throwing an error?

James Ang

Hi Yair,

This is great. However, the interactive screen capture doesn't work for me.

% imageData = screencapture; % interactively select screen-capture rectangle

any advise? I'm using R2015b.

Thanks in advance.

Yair Altman

@Dwight - I uploaded a variant of your suggested fix. Sorry for misspelling your name...

Dwight Bartholomew

I had a problem using the function when deployed as an executable. I modified the imclipboard(imgData) function and it works.

% Add the necessary Java class (ImageSelection) to the Java classpath
if ~exist('ImageSelection', 'class')

% Obtain the directory of the executable (or of the M-file if no deployed)
if isdeployed % Stand-alone mode.
[status, result] = system('path');
MatLabFilePath = char(regexpi(result, 'Path=(.*?);', 'tokens', 'once'));
else % MATLAB mode.
[MatLabFilePath name ext] = fileparts(mfilename('fullpath'));
javaaddpath(MatLabFilePath, '-end');

% % javaaddpath(fileparts(which(mfilename)), '-end');


I have a problem with the function. If I use two monitors (main/sub) and run Matlab in main at first capturing certain rect area (rectPos). Then I turned off my main monitor, everything of desktop goes to sub monitor including Matlab, the same function call with adjusted new rectPos will not provide the same image as in main monitor (there is a black area). Only restart Matlab solve this problem. Is there a way not to restart Matlab??


Hello Yair, this is really good stuff. However, I use the spectrum analyser block in a Simulink model, and wonder if / how this could be used to capture the spectrum window.Thanks.


Marc Lalancette

Amazing and sorely needed! Only way I found to save a figure properly.

Yair Altman

@Andy - you can use the ScreenCapture function within a Matlab s-function block in your Simulink model. The input should be a Matlab figure handle, it does not recognize models as a valid input.


Is there a way to use this in Simulink? I tried running the file, but it didn't like the imports in lines 755-777. I tried calling those first then running the rest of the code, but got more errors that way.

Fernando Esteves

Ok, thanks for the answer Yair.

Yair Altman

@Fernando - when you take a screenshot, the resolution is exactly the displayed resolution of the figure window - exactly the same number of pixels as displayed onscreen. To resize a figure, update its Position property. If you need a vectorized (scalable) image, then you should save the figure as an EPS/WMF and not use this utility.

Fernando Esteves

Magnificent code Yair, thanks.

I have two questions. Is there a way to set the position (horizontally or vertically) and size of the figure for printing? and How can I increase the resolution of the jpg or png image?

Fernando Esteves


can someone provide a code that can take multiple screen captures per second for certain amount time,and without manually selecting the area of interest.Thanks.



5 more stars from me as it now works perfect in 2014b !

Yair Altman

@Yannick - I just uploaded a fixed version that should also work on R2014b (as well as on older Matlab releases).


It worked perfect until 2014b.

Now if I do :
"peaks, imdata=screencapture(gcf); imshow(imdata)"
All I get is a black image.
What's the trick for the latest release ?

Hoi Wong

With TMW never getting figures to print/export right without font size/positions being distorted. This tool is a lifesaver.


Shalin Mehta

Works well. Allowed me to capture a screen-shot of panel!

Shalin Mehta


Great tool,it does exactly what i need!!



Ok fair enough. But the other issue I have is that the rect used to specify the position is not consistent with java coordinates (mentioned in your code). These have coordinates at top left - yours is bottom left and for some inexplicable reason (0,0) is off screen in your coordinate system. I see there are "estimated uncertainties" but where do these come from? Should be just a simple translation/reflection between the two with zero uncertainty. I can reverse engineer the offset and subtract it out but will this be different each time?

Yair Altman

Murray - that's the entire point: the only way to interactively select a screen-capture box anywhere on the desktop (not just within a Matlab figure) is to create an almost-transparent figure that spans the entire desktop area, and then let the user click-and-drag within it. You don't need to find the edges at all - simply drag a box of your requested screen-capture area and then the almost-transparent window will disappear and you will get your desired screen-capture.

A technical explanation is provided here:


The mouse click window for interactively selecting a target area doesn't appear to work very well. A window appears and then disappears (almost) when the prompt comes up but it remains almost invisible - pretty much impossible to find the edges.

Yair Altman

Hannu - you are using the utility incorrectly. Look at the usage examples in the description for examples.

Hannu K

screencapture(axesHandle,'target','filename.jpg') seems to save an image that's all black. The same thing happens if I give the gcf handle as an input.

The axes is in a gui with many other axes. I use guy layout -toolbox to position everything if that matters anything. I also use openGL renderer as I need transparency but I tried painters with similar results.

If I simply call screencapture() I get the Mouse click -prompt, but when I press ok the prompt and my gui become unselectable. If i press the Matlab-icon in my windows7 toolbar I see a new blank Matlab figure named 'Figure2' in the preview but I can't select it. I can still close it from the red cross and after that the prompt and my gui become selectable once again but no figure is saved of course.

What am I doing wrong?

Jack Kohoutek

Excellent, succeeds where getframe fails with complicated figures w/ subfigures and axes

Yair Altman

@Philipp - this is a byproduct of the builtin javaaddpath function, as you have found. It is a limitation of this function that has existed for ages and as far as I know has no known workaround. You might try to contact MathWorks to ask for this to be fixed, but don't hold your hopes too high...

Philipp Pruefer

I found a small problem that I can’t fix in the code.

I am using ScreenCapture in a GUI where I have defined a few global variables. All those variables are deleted when I run ScreenCapture for the first time. I traced it back to the following function 'javaaddpath' which seems to delete my global variables. It is only called for the first time I run ScreenCapture as afterwards the java file is loaded.

% Add the necessary Java class (ImageSelection) to the Java classpath
if ~exist('ImageSelection', 'class')
javaaddpath([cd,'\Tools\ScreenCapture'], '-end');

My workaround is to load the java class during GUI loading. But maybe there is a better way of managing this in the script? Maybe there is a problem with my Matlab version which is 7.13 at the moment. Maybe it is time to upgrade…

Philipp Pruefer


Fails with R2013b, on OSX Mavericks.

In fact, this seems to be an OSX/JVM issue.

in imclipboard: Data translation failed: not an image format

java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)


Fails with R2013b, on OSX Mavericks.

In fact, this seems to be an OSX/JVM issue. Data translation failed: not an image format

Yair Altman

@Hong - you would need to know the exact pixel position vector of the external application and then you could use ScreenCapture on it from within Matlab. I do not know of an easy way to programmatically get the position vector for an external process, but I assume that it's possible - you'll need to search online for a solution I'm afraid.


Excellent job, thank you so much!

However, since I am not very familiar with matlab, I would like to ask how can I screencapture an area in other application, for example Chrome, such that I can keep monitoring the application and response to it in later stages? Thank you so much!


Works well, but seems to not be compilable.

Oliver Woodford

Great tool. Worked when getframe() didn't.

Maysam Shahedi

It's cool!

Adam Filion


Yair Altman

@Mikhail - ScreenCapture uses java.awt.Robot, which only captures a bitmap image


Very nice!

How about capturing to a vector file format instead of a bitmap?


Yair Altman

@Lapili Sanchez - the screencapture code already contains a corrected version of us's code - it was corrected in the code after "us" posted his comment above.

Moreover, this code is currently not used, since I have included even faster code, based on Jan Simon's comment. It is Jan Simon's faster code that is the current infrastructure of screencapture.

Take a look at the getScreenCaptureImageData() function within screencapture.m for more information

lapili Sanchez

>> % macro
>> conv=@(a,b,c) double(bitand(a,255^b))./255^c;

Just a small correction, that sentence from 'us' code should be:
conv=@(a,b,c) double(bitand(a,256^b-256^(b-1)))./256^c;

Thanks anyway, that code is so fast!

Yanxiong Li


Dinie Muhammad


Thanks Yair! The new version works for Matlab 6.5, if you download James Tursa's typecast replacement from the FEX (#17476).
Capturing the whole screen does not match the edges exactly. E.g. this is exact:
img = screencapture(0, 'Position', [1,-2,1024,768]);
But then the top left three pixels are [255,0,0], [0,255,0] and [0,0,255]. The rest of the image is fine. Under Matlab 2009a these funny pixels do not appear.


Thanks for this exhaustively implemented screen capture tool. It works with some tiny modifications even in Matlab 6.5.
The conversion from the INT32 from getDataStorage to a Matlab RGB array can be done in the half time. Just let TYPECAST split the INT32 values instead of expensive BITSHIFT and BITAND (line 401):
pixelsData = reshape(typecast( ...
jImage.getData.getDataStorage, 'uint8'), 4, w, h);
imgData = cat(3, ...
transpose(reshape(pixelsData(3, :, :), w, h)), ...
transpose(reshape(pixelsData(2, :, :), w, h)), ...
transpose(reshape(pixelsData(1, :, :), w, h)));
This is the most time consuming part and a further acceleration might be useful.


a very nice robot, which the FEX community has been looking for a long time...
two thoughts:
1) in interactive mode, the user looses the data if no output arg is selected, which may be a bit frustrating:
a) a warning(?)
b) a new figure displaying the result by default(?)
2) we've been using this approach, which may be a bit faster (depending on the size of the capture) by converting the planes in one shot using a macro...

% input
% xoff/yoff/xlen/ylen
% assign after loading java stuff...
% macro
conv=@(a,b,c) double(bitand(a,255^b))./255^c;
% capture screen contents at this pos
mm(:,:,3)=conv(buf,1,0); % bitand(buf,255^1)./255^0;
mm(:,:,2)=conv(buf,2,1); % bitand(buf,255^2)./255^1;
mm(:,:,1)=conv(buf,3,2); % bitand(buf,255^3)./255^2;
% ...for display in a regular figure
axis image;
axis off;

3) in principle, the robot itself can be used on any screen location; it would be nice - however, admittedly cumbersome - to add this feature


MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!