press a button replace an image, cp5.

I'm using cp5 to build a little particle sketch and I need to be able to replace an image from the interface. I have trouble finding out:

  • how to open a file requester.
  • how to load a new image in to an already existing declared image.

I've been trying the file requester code in 'javax.swing.*' but I don't really understand what I'm doing and although the code should only triggered when a cp5 button is pressed when I compile the sketch and run it the file dialogue shows up when the sketch starts. Tres bizarre.

Any ideas?

Answers

  • Hi! Processing already includes a file selector.

    PImage myImage;
    
    void setup() {
      size(600, 600);
      println("Click to load a new image");
    }
    void draw() {
    }
    void mousePressed() {
      selectInput("Select a file to process:", "fileSelected");
    }
    
    void fileSelected(File selection) {
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else {
        String path = selection.getAbsolutePath();
        myImage = loadImage(path);
        image(myImage, 0, 0);
      }
    }
    

    You should add file-type checking to avoid trying to load non-image files as images (you could just check that the path ends in ".jpg" for instance).

Sign In or Register to comment.