Images in Processing

The final part of the KKB210: Computational Arts 1 week 4 tutorial was to import an image and make use of it. Processing supports .gif, .jpg, .tga and .png image formats.

First off, put the image you plan to use in the same folder as the .pde of the file you are working on, keeping in mind that it must be one of the four common formats supported by Processing.

The sketch we will be making will be very similar and will use much of the same code as the previous exercise, so if you have it saved, you could use it as the basis for this exercise.

Setting up the canvas is slightly different to what we have done before in order to include the image, but it is easy enough to follow.

// Variables for random numbers for position and size.
int x1, x2, y1, y2;

// Position and size variables that will be modified.
int boxWidth=250;
int boxHeight=250;
int boxX=100;
int boxY=100;

// Creating the image variable.
PImage laptop;

void setup(){
size(500,500);
// Assigning the image to the variable.
laptop = loadImage("laptop.JPG");
}

void draw() {

PImage object is the datatype that holds images, so an image variable has to be created using PImage. I am using a photo of my laptop since that is the first thing I came across while doing the tutorial, so I have named my variable “laptop”.

As part of the setup, we assign the image to the variable. You can use relative paths, but it is easier if you just copy the photo into the same folder as the .pde.

We load the image into the variable using laptop = loadImage(“laptop.JPG”); within the setup(){}.

Moving onto the rest of the sketch, the majority of it stays the same as the previous exercise. The only change is that we can get rid of the (r,g,b) variables as well as fill() and rect(). We will be replacing these with an image object.

So we should have something like this:

fill(0,0,250,10);
rect(0,0,width,height);

x1 = int(random(6)-3);
x2 = int(random(6)-3);
y1 = int(random(6)-3);
y2 = int(random(6)-3);

boxX += x1;
boxY += y1;
boxWidth += x2;
boxHeight += y2;

// This replaces the rect and fill.
image(laptop,boxX,boxY,boxWidth,boxHeight);
}

We don’t need fill because we already have a coloured image.

So finally, you should have something that looks like this:

int x1, x2, y1, y2;

int boxWidth=250;
int boxHeight=250;
int boxX=100;
int boxY=100;

int r=150;
int g=140;
int b=180;

PImage laptop;

void setup(){
size(500,500);
laptop = loadImage("laptop.JPG");
}

void draw() {
fill(0,0,250,10);
rect(0,0,width,height);

x1 = int(random(6)-3);
x2 = int(random(6)-3);
y1 = int(random(6)-3);
y2 = int(random(6)-3);

boxX += x1;
boxY += y1;
boxWidth += x2;
boxHeight += y2;

r += int(random(4)-2);
g += int(random(4)-2);
b += int(random(4)-2);

//fill(r,g,b);
//rect(boxX,boxY,boxWidth,boxHeight);
image(laptop,boxX,boxY,boxWidth,boxHeight);
}

Have a look at my Java applet to see how it should render.

Tags: , , ,

Leave a Reply