Search code examples
p5.js

p5js Getting pixels from image using loadPixels() method


The p5js documentation suggests that you should be able to call loadPixels() on an image object, however whenever I try I get an empty pixels array out of it.

I can paint the image to the canvas with a call to image, and then do a loadPixels() without a calling object which returns to the pixel data for the canvas without a problem.

Am I missing something that is needed in order for this to work?

let img;

function preload() {
  img = loadImage("image.jpg");
}

function setup() {
  createCanvas(400, 400);
  img.loadPixels();
  console.log(pixels.length);
}

Solution

  • Yep. You are printing the wrong pixels array, the one for canvas, not the one you want, for the image.

    You should say:

    console.log(img.pixels.length);
    
    

    to print the length of img.pixels ;)