Taking Screenshots with Processing

Posted by Jan Vantomme on 19 February 2014.
Tags:

Sometimes it can be handy to create a screenshot from Processing. In this short tutorial, I’m going to show you how you can do this in Processing 2. I’ve used this code to create a new piece of net art named Screenshot Inception.

Import these Java classes at the beginning of your sketch and declare a PImage variable. You also need some basic code in the setup() and draw() functions.

import java.awt.Robot;
import java.awt.*;
import java.awt.image.*;

PImage screenShot;

void setup()
{
    size
displayWidthdisplayHeight );

    
takeScreenShot();

    
background);
}

void draw
()
{
    image
screenShot0);

The function to take a screenshot is fairly straightforward. You need to create a Java Rectangle and copy the screen dimensions into that Rectangle. The Robot class is used to capture the screen into a BufferedImage using the createScreenCapture() method. The pixels from the BufferedImage are then copied into a PImage object with the same dimensions. Make sure you use this code within a try/catch block or you’ll get an error.

void takeScreenShot()
{
    Rectangle screenRect 
= new RectangleToolkit.getDefaultToolkit().getScreenSize() );
    
    try 
{
        
        BufferedImage screenBuffer 
= new Robot().createScreenCapturescreenRect );
        
        
screenShot = new PImagescreenBuffer.getWidth(), screenBuffer.getHeight(), PConstants.ARGB );
        
screenBuffer.getRGB00screenShot.widthscreenShot.heightscreenShot.pixels0screenShot.width );
        
screenShot.updatePixels();
        
    
catch ( AWTException e {
        e
.printStackTrace();
    
}

The code for this tutorial is available on GitHub.

Tweet this article