How do I take a screenshot using MATLAB?

295 views (last 30 days)
Is there a way that I could use MATLAB the same way that I use software such as snipping tool or print screen? For example, I would like to run a code and save an image from a rectangular box on the screen. Is this possible?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 30 Jun 2021
Edited: MathWorks Support Team on 30 Jun 2021
This is possible to do in MATLAB by using Java libraries.
% Take screen capture
robot = java.awt.Robot();
pos = [0 0 400 400]; % [left top width height]
rect = java.awt.Rectangle(pos(1),pos(2),pos(3),pos(4));
cap = robot.createScreenCapture(rect);
% Convert to an RGB image
rgb = typecast(cap.getRGB(0,0,cap.getWidth,cap.getHeight,[],0,cap.getWidth),'uint8');
imgData = zeros(cap.getHeight,cap.getWidth,3,'uint8');
imgData(:,:,1) = reshape(rgb(3:4:end),cap.getWidth,[])';
imgData(:,:,2) = reshape(rgb(2:4:end),cap.getWidth,[])';
imgData(:,:,3) = reshape(rgb(1:4:end),cap.getWidth,[])';
% Show or save to file
imshow(imgData)
imwrite(imgData,'out.png')
Note: If you are looking to take a screenshot of a figure window, there are many other tools that are much better suited for this, for example the "print" and "getframe" functions, as well as several featured submissions to File Exchange such as "ScreenCapture" or "export_fig".
  2 Comments
Biraj Khanal
Biraj Khanal on 6 Jan 2022 at 15:32
I am trying to take a screenshot of a figure window like you said.
plot(rand(200,200));
set(gcf,'renderer','painters');
exportgraphics(gca,'plot2.emf');
% Take screen capture
robot = java.awt.Robot();
pos = [700 100 500 400]; % [left top width height]
rect = java.awt.Rectangle(pos(1),pos(2),pos(3),pos(4));
cap = robot.createScreenCapture(rect);
% Convert to an RGB image
rgb = typecast(cap.getRGB(0,0,cap.getWidth,cap.getHeight,[],0,cap.getWidth),'uint8');
imgData = zeros(cap.getHeight,cap.getWidth,3,'uint8');
imgData(:,:,1) = reshape(rgb(3:4:end),cap.getWidth,[])';
imgData(:,:,2) = reshape(rgb(2:4:end),cap.getWidth,[])';
imgData(:,:,3) = reshape(rgb(1:4:end),cap.getWidth,[])';
% Show or save to file
%imshow(imgData);
imwrite(imgData,'out.png');
For some reason, this would only work till I have the exportgraphics line. If I comment it out, the screen capture will close the figure and then take a snip which is useless. I cannot understand the process.
Can somone suggest something?
This working would save a ton of my time :D

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by