Home > Back-end >  Random image import in processing
Random image import in processing

Time:12-03

I am working on a project in processing at the moment and I would like to import a different random image for each frame every time. Is this even possible? ideally I would like to fill a folder with images and have the program pull a different random image each frame but I am unsure if this can be done. Code to pull a single image is below.

I would think putting loadImage in the draw loop would work, but is there a way to call a random image from a folder?

PImage myImage;

void setup() {    
    size(400, 400);    
    myImage = loadImage("wood.jpeg");    
    myImage.loadPixels();
}

void draw() {
    image(myImage, 100, 100, 200, 200);
}

CodePudding user response:

You can start by listing all the files in the directory

    File folder = new File("your/path");
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i  ) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File "   listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory "   listOfFiles[i].getName());
      }
    }

And then use the random function to look for the file you want to use

    File randomElement = listOfFiles.get(rand.nextInt(listOfFiles.size()));

CodePudding user response:

To get a random file from a folder :

File folder = new File("path/to/images/folder");
List<File> filesList = Arrays.asList(folder.listFiles());
Collections.shuffle(filesList);
File file = filesList.get(0); // a random file 
  • Related