P5.js image width and height error

Hello there,

Basically I want to load some images (in the folder pics/n*.jpg) and get their pixel data in a 2d array (data = []).

I have this code :

let data = [];
let img;

function preload() {
    for (let i = 0; i < 5; i++) {
        img = loadImage('pics/n' + (i + 1) + '.jpg');
        console.log(img);


        let xs = [];
        img.loadPixels();
        for (let j = 0; j < img.pixels.length; j += 4) {
            xs.push(img.pixels[j]);
        }
        data.push(xs);
        
    }
    console.log(data);
}

function setup() {
    createCanvas(500, 500);
}

function draw() {
    noLoop();
}

When I console.log the images I loaded with loadImage(), their width and height are 1 but their propreties width and height are the right ones (172*254).

Can somebody explain this to me ? :

image

UPDATE :

More generally when I try to load an image when I concatenate strings and numbers, there’s the same error :

function setup() {
    createCanvas(500, 500);
    let img = loadImage('pics/n'+5+'.jpg');
    console.log(img);
}

But it works when I use a callback function :

function setup(){
    createCanvas(500,500);
    let img = loadImage('pics/n'+5+'.jpg', () => {
        console.log(img);
        image(img,0,0);
    });
}
1 Like

I believe it is because the image isn’t fully loaded, so neither is the width and height. However, once the images have been loaded, and the callback function is called, the width and height have been established.

You can also try loading the images in preload() but console logging them in setup (rather than in the callback function) as “setup() will wait until any load calls within have finished”.

3 Likes

Thanks for your answer, I understand the case when I try to console.log images inside the preload() function.
What about the case when I try to console.log the image in the setup() function?

function setup() {
    createCanvas(500, 500);
    let img = loadImage('pics/n'+5+'.jpg');
    console.log(img);
}
1 Like

You are still trying to access data from the image before it has fully loaded! You are using the image the line after it has been loaded! The callback function and setup and forced to wait for preload but the next line of setup hasn’t been told to only run once the image that started loading the line before has finished loading.

3 Likes

Oh ok got it !

Thanks

1 Like