Skip to content

Images

Processing lets you use existing images easily as long as you know the name of the image file and which directory it is in. For the next example, you will need to do two things:

  • Create a directory on your PC called C:\temp

  • Right-click this image file link to download the file into the directory you have just created.

When you have done that, load the code into the PDE and run it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    PImage img1;

    void setup() {
      fullScreen();

      img1 = loadImage("C:/temp/Penguin.png");

      background(255,255,255);
      image(img1,width/2-img1.width/2, height/2-img1.height/2);
    }

Here is an explanation of the code line by line:

Line Command Description
1 PImage img1; Declares the variable img1 of type PImage.
6 img1 = loadImage("C:/temp/Penguin.png"); Loads the image from a file.
12 image(img1, width/2-img1.width/2, height/2-img1.height/2); Displays the image in the centre of the screen.

The calculation takes account of the height and width of the image itself

Another way to place the image at the centre of the screen is to start with it centred on the origin, and then to move it. This may seem like a strange thing to do, but it means that we can introduce some simple animations. Start by copying the code below into the PDE and running it. You should see the same thing: the penguin appears in the centre of the display.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    PImage img1;

    void setup() {
      fullScreen();
      img1 = loadImage("C:/temp/Penguin.png");
    }

    void draw() {
      background(255,255,255);
      translate(width/2, height/2);
      image(img1,-img1.width/2, -img1.height/2);
    }

This new code also places the drawing commands into the draw() function. That means that the image is redrawn every time that the function repeats. That is quite wasteful if the image does not change. However, with one further change we can create an interesting effect. Copy the code from the next box into the PDE and run it. Spend some time looking at how it is different from the previous version.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    PImage img1;
    float angle;

    void setup() {
      fullScreen();
      img1 = loadImage("C:/temp/Penguin.png");
      angle = 0;
    }

    void draw() {
      background(255,255,255);
      translate(width/2, height/2);
      rotate(angle += 0.1);
      image(img1,-img1.width/2, -img1.height/2);
    }

Challenge

See it you can work out how to make the penguin rotate faster or more slowly.