how to load images ignoring file names and extensions

hi, like this i can load images named v, numbered 01,02... and with extension .jpg but how to load all images from data folder ignoring the file names and extensions, so i don't need to rename all of them before loading?

PImage[] p = new PImage[20];

for (int i = 0; i < p.length; i++) {
    p[i] = loadImage("v"+nf(i, 2) + ".jpg"); // how to rewrite this?
  }

Answers

  • edited July 2014

    Similar to what I did below:
    http://forum.processing.org/two/discussion/6104/associate-text-and-picture

    // forum.processing.org/two/discussion/6115/
    // how-to-load-images-ignoring-file-names-and-extensions
    
    static final String NAME = "v", EXT = ".jpg";
    static final int NUM = 20;
    final PImage[] imgs = new PImage[NUM];
    
    void setup() {
      size(800, 600, JAVA2D);
      smooth(4);
    
      for (int i = 0; i != NUM; imgs[i++] = loadImage(
        NAME + nf(i, 2) + EXT));
    }
    
  • that's not what he wants, because it's exactly the same as what he has, only four times longer and less readable.

    read up on java Files. the listFiles() method will give you a list of files. iterate over them and call loadImage for each. they will all have to be images but anything that loadImage() can handle should be ok.

    http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()

  • edited July 2014

    Oh, if that's the case, I've got a solution from this thread below:
    http://forum.processing.org/two/discussion/2578/how-to-filter-and-order-a-set-of-files

    More relevant parts:


    import java.io.FilenameFilter;
    
    static final FilenameFilter pictFilter = new FilenameFilter() {
      final String[] exts = {
        ".png", ".jpg", ".jpeg", ".gif"
      };
    
      @ Override boolean accept(final File dir, String name) {
        name = name.toLowerCase();
        for (final String ext: exts)  if (name.endsWith(ext))  return true;
        return false;
      }
    };
    

    protected static final File[] getFolderContent(final File dir) {
      return dir.listFiles(pictFilter);
    }
    

    PImage[] imgs;
    
    void setup() {
      File[] imgFiles = getFolderContent(new File(dataPath("")));
      java.util.Arrays.sort(imgFiles);
      println(imgFiles);
    
      imgs = new PImage[imgFiles.length];
    
      for (int i = 0; i != imgs.length;
        imgs[i] = loadImage(imgFiles[i++].toString()));
    
      exit();
    }
    

  • stfstf
    edited July 2014

    "ignoring file names and extensions...?" Could it look like this:

    File fileObj = new File (pathToPix);
    String [] contents = fileObj.list();
    

    ?

  • edited July 2014
    File fileObj = new File (pathToPix);
    String [] contents = fileObj.list();
    

    this works fine when all pics is added to sketch

    only typing in path to pictures folder doesn't

Sign In or Register to comment.