Search code examples
processing

Randomize image when mouse pressed - Processing


  • I'm trying to make a grid where each individual cell contains one random image from my data folder.

  • So far, I've accomplished having a different image in every cell, but it doesn't randomize

  • instead of randomly picking one from the 600+ from the folder, it places every image in order 1 to 27.

  • Apart from that, I want it to randomize every time I click with the mouse instead of just randomizing when its closed and played again. The code:

    PImage img[];
    int nPics;
     
    int w;
    int h;
    
    
    int rand;
    
     
    void setup(){
      
      size(1500,500);
      nPics=27;
      img = new PImage[nPics];
    
      w=width/9;  
      h=height/3; 
    
    for (int i = 0; i <nPics; i++) {
        img[i] = loadImage("img_" +nf(i,3)+ ".jpg");
        imageMode(CORNERS);
      }

      //rand = int(random(0,687));
      //img[0]=loadImage("img_" + nf(rand,3)+ ".jpg");

    }
     
    void draw(){
    background(0);
      for(int i=0;i<nPics;i=i+3){  
         int col = i/3;
         for(int row=0;row<3;row++)
           image(img[i+row],col*w,row*h,(col+1)*w,(row+1)*h);
      }
      
    }

Solution

  • When you are loading your images you are using i instead of rand. In order to randomize the images when you click the mouse, you can use the mousePressed() to reload different images into your array.

    This should work:

    PImage img[];
    int nPics;
    
    int w, h;
    
    void loadImages(){
      for (int i = 0; i < nPics; i++) {
        img[i] = loadImage("img_"+ nf(int(random(0, 687)), 3) + ".jpg");
        imageMode(CORNERS);
      }
    }
    
    void setup() {
      size(1500, 500);
      nPics=27;
      img = new PImage[nPics];
    
      w=width/9;  
      h=height/3; 
    
      loadImages();
    }
    
    void mousePressed(){
      loadImages();
    }
    
    void draw() {
      background(0);
      for (int i=0; i<nPics; i=i+3) {  
        int col = i/3;
        for (int row=0; row<3; row++)
          image(img[i+row], col*w, row*h, (col+1)*w, (row+1)*h);
      }
    }