Search code examples
javaanimationzipcontainersslick2d

Load containerfile in Java


I have the problem in Slick that I want to load a custom containerfile(Which contains for example a few hundred images). But how in the hell do I do that? I use Slick for my game which will have animations. Slick needs for its animations a imagearray. Imagine now, if you want to display a bit complexer animation which consists of 300 images, manual loading and creating imageobjects is a pure pain in the ass process. To fix that, I have such a containerclass in mind which opens the container and returns me the images(or anything else!). Saving images back to the container would be also cool :P

So any ideas?

Thanks for any tips how to solve that in advance.

Greetings


Solution

  • If you have all your images in a directory or file directory, its pretty easy to traverse the directories and make a list or map of all the images via java's File class and some recursion. Something like...

    Map <String, Image> nameToImage = new HashMap<>();
    public void addDefaultImages(){
        this.addAndRecurseDirectoryOfImages(DEFAULT_IMAGE_DIRECTORY);
    }
    
    public void addAndRecurseDirectoryOfImages(String directory) {
        File folder = new File(directory);
        File[] listOfFiles = folder.listFiles();
    
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                nameToImage.put(listOfFiles[i].getName(), new Image(directory + "/" + listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                addAndRecurseDirectoryOfImages(directory + "/" + listOfFiles[i].getName());
            }
        }
    }
    

    Then you can get images via the image name:

    nameToImage.get(filename);
    

    You can also add some logic to strip off the file extension.

    BUT! There is a catch! If you package your application up one day, say, in a .jar file, Jar files have no concept of a file system! Meaning this won't work! In that case you'll want to generate a file that has a list of all your image locations because you won't be able to traverse directories.