Can a function like this load images?

I wrote a function assuming that I could pass to an array of images, an array of strings and the length of the two of them and it would have loaded the images, stored into the strings, in the elements of the images array; but when I’m about to call the function inside of the void setup() function to load the images I want to load in that moment, it sends out to me a NullPointerException error, so I can’t run my program. Could someone explain me why?
Here’s the function source code:

PImage[] imgLoader(PImage img[], String fileName[], int n) {
  
  for (int a=0; a<n; a++)
    img[a]=loadImage(fileName[a]);
  return img;
}
1 Like

Hi! sorry but it’s been a long time since use Processing… and i don’t remember if the way that you declare the arguments is the correct. You can try PImage[] img, etc… But i don’t know if that function is the correct approach. You should try to create a function that only loads the image, like:

PImage imgLoader(PImage img, String filename){
   img = loadImage(filename);
   return img;
}

And then, create another function who calls the imgLoader function, or simple run it over a for loop.

PImage[] images;
for(int a = 0; a < n; a++){
images[a] = imgLoader(img[a], str[a]); 
}

where img and str are the arrays where you’ve stored those files.

Hey,

without the context, where you are using the function, it’s hard to tell where your error comes from. But think you could make thins a little simpler. First you could either pass an image-array OR you return one after loading the specified files.

Here is an example with a slightly simplified version of your function:

void setup() {
  // file names
  String[] myStringArray = {"img_01.jpg", "img_02.jpg", "img_03.jpg", "img_04.jpg", "img_05.jpg"};

  // get an image-array from your loading function
  PImage[] myImageArray = imgLoader(myStringArray);
}


PImage[] imgLoader(String fileNames[]) {
  // create array with same length as filenames-array
  PImage[] images = new PImage[fileNames.length];

  // load all images
  for (int i=0; i<fileNames.length; i++)
    images[i]=loadImage(fileNames[i]);

  // return the image-array
  return images;
}

2 Likes