Taking Screenshots with Processing

Posted by Jan Vantomme on 19 February 2014.

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()
displayWidthdisplayHeight );



void draw

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() );
        BufferedImage screenBuffer 
= new Robot().createScreenCapturescreenRect );
screenShot = new PImagescreenBuffer.getWidth(), screenBuffer.getHeight(), PConstants.ARGB );
screenBuffer.getRGB00screenShot.widthscreenShot.heightscreenShot.pixels0screenShot.width );
catch ( AWTException e {

The code for this tutorial is available on GitHub.

Tweet this article