Using images in p5


You can load image and audio files in p5.

The files are loaded by the sketch so don’t forget to copy them wherever you want to use your filed.

Find an image and put it in the a folder called “assets” inside your project folder

Loading an image can take some times so it’s good practice to load the image inside a function called preload:

//1- Declare variable for your image
var img; 

//2- Preload the image (replace the name and path with your own)
// preload() runs once before setup
function preload() {  
  img = loadImage("assets/imageName.png");
}

function setup() {
  createCanvas(720, 400);
}

function draw() {
  //3- Displays the image at its actual size at point (0,0)
  image(img, 0, 0);
  
  //You can also resize the image
  // Displays the image at point (0, height/2) at half size
  //image(img, 0, height/2, img.width/2, img.height/2);
}

It works with alpha too!
(How to add an alpha channel in photoshop)

Create a scene with a background and an object following the mouse.

Filters
Try to call the function tint before displaying the image:

image(img, 0, 0);
tint(0, 153, 204);  // Tint blue r,g,b,a (add one parameter for alpha) 
image(img, 50, 0);

You can also use tint to change only the transparency

image(img, 0, 0);
tint(255, 126); 
image(img, 50, 0);

Try some other effects using the filter and blend functions

Transformations
Transformations can be applied to images as well:

//change to center to facilitate rotation
imageMode(CENTER);
 
  push();
    translate(150, 150);
    rotate(radians(45));
    image(img, 0, 0, 200, 200);
  pop();

Posted in