Taking a Screenshot (Screen Capture) using MATLAB Code

How you take a screenshot of your computer's screen till now?
With the "Print Screen" key and then pasting the shot in Paint or Other software?
Well, that's an old way now! You can use your MATLAB code to take a screenshot of the current screen.
Using the Java's Robot Class function which can be imported in MATLAB.

MATLAB with a figure window showing the screenshot of the current screen
MATLAB with a figure window showing the screenshot of the current screen

Here is the MATLAB code for doing a Screen Capture (Comments Bolded).....

close all

import java.awt.Robot;
vks = Robot; %Creating a Robot object

import java.awt.Rectangle;
rect = Rectangle; %Creating a Rectangle object 

import java.awt.Toolkit.getDefaultToolkit;
tool = getDefaultToolkit; %Creating a Toolkit object

screenDim = tool.getScreenSize; %Getting the screen size

width = screenDim.width; %Width of screen
height = screenDim.height; %Height of screen

rect.setRect(0, 0, width, height); %Setting the size of screen capture

screen = vks.createScreenCapture(rect); %capturing the screen

pixelsData = reshape(typecast(screen.getData.getDataStorage, 'uint8'), 4, width, height);
%Converting to 8 Bit data

imgData = zeros([height,width,3],'uint8'); %Create the image variable
imgData(:,:,1) = transpose(reshape(pixelsData(3, :, :), width, height));
imgData(:,:,2) = transpose(reshape(pixelsData(2, :, :), width, height));
imgData(:,:,3) = transpose(reshape(pixelsData(1, :, :), width, height));
%Save image data B-G-R Plane wise

imshow(imgData) %Show the captured screenshot
imwrite(imgData, 'ScreenCaptureMatlab.jpg'); %Save the captured screenshot
%End of code

Further, you can control the size of the screenshot with a slide modification in the above code! You can also introduce a finite delay between the start of the code and the screen capture step so that you can minimize MATLAB and open the window/screen of your choice.

Have you got a great idea with this code or the Java Robot class in MATLAB? You can share in the comments!

Author: Vibhutesh Kumar Singh
An active & prominent author at Digital iVision Labs! Like to write about MATLAB, C++, Arduino, OpenCV, NI Labview, Web Designing & other Electronics stuffs! Finished up M.Tech. From IIIT Delhi, now doing PhD in wireless communication with prominent researchers University College Dublin (CONNECT CENTRE). Drop a mail: vibhutesh[at]gmail.com to ask something about the article or Follow him at....