Taking Screenshots with Processing

Posted on 2014-02-19 by Jan Vantomme
Tags: processing, tutorial

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( displayWidth, displayHeight );

    takeScreenShot();

    background( 0 );
}

void draw()
{
    image( screenShot, 0, 0 );
}

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 Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );

    try {

        BufferedImage screenBuffer = new Robot().createScreenCapture( screenRect );

        screenShot = new PImage( screenBuffer.getWidth(), screenBuffer.getHeight(), PConstants.ARGB );
        screenBuffer.getRGB( 0, 0, screenShot.width, screenShot.height, screenShot.pixels, 0, screenShot.width );
        screenShot.updatePixels();

    } catch ( AWTException e ) {
        e.printStackTrace();
    }
}

The code for this tutorial is available on GitHub.

Tweet this article