Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (581)
games submitted by our members
Games in WIP (500)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Slick2D automatically load images?  (Read 984 times)
0 Members and 1 Guest are viewing this topic.
Offline FireFreek

Senior Newbie


Projects: 1



« Posted 2012-06-11 04:56:10 »

So, while I was working on a game I was making, I made myself a little Art class. Here it is:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
package com.kirc.drilldescent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.AngelCodeFont;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;

public class Art
{
   
//   public static Image dirtTile;
  private static Map<String,Image> loadedImages;
   private static AngelCodeFont font;
   /**
    * Loads all .png images located in the /res folder.
    * @throws SlickException
    */

   public static void init() throws SlickException {
     
//      dirtTile = new Image("res/dirtTile.png");
     loadedImages = new HashMap<>();
      try
      {
         URI uri = new URI(ResourceLoader.getResource("res").toString());
         File[] files = new File(uri).listFiles(new FilenameFilter(){

            @Override
            public boolean accept(File dir, String name)
            {
               if(name.endsWith(".png"))
                  return true;
               return false;
            }
           
         });
         
         for(File f:files)
         {
            FileInputStream fis = new FileInputStream(f);
            Image image = new Image(fis, "res/"+f.getName(), false);
            loadedImages.put(f.getName(), image);
         }
      } catch (URISyntaxException | FileNotFoundException e)
      {
         System.err.println("UNABLE TO LOAD IMAGES FROM RES FOLDER!");
         e.printStackTrace();
      }
     
      font = new AngelCodeFont("res/bitmapfont.fnt",Art.get("bitmapfont.png"));

   }
   /**
    *
    * @param filename The filename of the image in the /res folder
    * @return The loaded image of that filename
    */

   public static Image get(String filename)
   {
      return loadedImages.get(filename);
   }
   
   public static AngelCodeFont getFont()
   {
      return font;
   }
}


Unfortunately, while this will automatically load all images in my res/ directory (and let me load them once and only once), it won't work if I decide to pack everything into a .jar. I was wondering if anyone used a nicer pattern to keep all their game art organized and easy to access in their code. I took the lazy way because I didn't want to add a line for every single one of my images. (Also, if you know how to adapt this to a .jar that'd be nice to share.)
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 605
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #1 - Posted 2012-06-11 13:00:02 »

You can iterate over the entries in a jar/zip file with

1  
2  
3  
4  
5  
6  
7  
8  
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

    ZipInputStream zis = new ZipInputStream(new FileInputStream(pathToZip));
    for (ZipEntry ze; (ze = zis.getNextEntry()) != null;) {
      System.out.println(ze.getName());
    }


That way you can enumerate all paths that start with "res/", ending with ".png" and load them using ClassLoader.getResourceAsStream(path).

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline FireFreek

Senior Newbie


Projects: 1



« Reply #2 - Posted 2012-06-11 14:04:47 »

Okay, but how do I get "pathToZip" to point to itself without having to keep the .jar strictly named? (If you use the .jar's name then you can't rename it or it won't work).
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 605
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #3 - Posted 2012-06-11 14:26:10 »

You could search it in the classpath.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline FireFreek

Senior Newbie


Projects: 1



« Reply #4 - Posted 2012-06-11 18:01:41 »

Well, got an answer from StackExchange. Figured i'd post the working code here for future reference:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
package com.kirc.drilldescent.res;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;

import org.newdawn.slick.AngelCodeFont;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;

public class Art
{
   
   private static Map<String,Image> loadedImages;
   private static AngelCodeFont font;
   /**
    * Loads all .png images located in source folders.
    * @throws SlickException
    */

   public static void init() throws SlickException {
     
      loadedImages = new HashMap<>();
      try
      {
         URL url = Art.class.getResource("../res");
         //use filesystem loading
        if(url != null)
         {
            File resDir = new File(new URI(url.toString()));
            File[] files = resDir.listFiles(new FilenameFilter(){
               @Override
               public boolean accept(File dir, String name)
               {
                  if(name.endsWith(".png"))
                     return true;
                  return false;
               }
               
            });
           
   
            for(File f:files)
            {
               FileInputStream fis = new FileInputStream(f);
               Image image = new Image(fis, f.getName(), false);
               loadedImages.put(f.getName(), image);
            }
         }
         //use jar loading
        else
         {
           
            URLConnection uc = ClassLoader.getSystemResource("com/kirc/drilldescent/res").openConnection();
            if(uc instanceof JarURLConnection)
            {
               JarURLConnection juc = (JarURLConnection) uc;
               JarFile jarFile = juc.getJarFile();
               Enumeration<JarEntry> jarFileEntries = jarFile.entries();
               while (jarFileEntries.hasMoreElements()) {
                  JarEntry jarEntry = jarFileEntries.nextElement();
                  String jarEntryName = jarEntry.getName();
                  if(jarEntryName.startsWith("com/kirc/drilldescent/res") && jarEntryName.endsWith(".png"))
                  {
                     Image image = new Image(jarEntryName);
                     loadedImages.put(jarEntryName.replace("com/kirc/drilldescent/res/",""),image);
                  }
                 
               }
            }
           
         }
      } catch (URISyntaxException | IOException e)
      {
         e.printStackTrace();
      }
     
      font = new AngelCodeFont("com/kirc/drilldescent/res/bitmapfont.fnt",Art.get("bitmapfont.png"));

   }
   /**
    *
    * @param filename The filename of the image in the /res folder
    * @return The loaded image of that filename
    */

   public static Image get(String filename)
   {
      return loadedImages.get(filename);
   }
   
   public static AngelCodeFont getFont()
   {
      return font;
   }
}


EDIT: Well, it works before I try to package the natives with jarsplice. After that, ClassLoader.getSystemResource fails to return anything. What does jarsplice do to prevent this from working? (I haven't actually got a clear idea what getSystemResource does either)
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (60 views)
2014-04-15 18:08:23

BurntPizza (58 views)
2014-04-15 03:46:01

UprightPath (71 views)
2014-04-14 17:39:50

UprightPath (54 views)
2014-04-14 17:35:47

Porlus (71 views)
2014-04-14 15:48:38

tom_mai78101 (97 views)
2014-04-10 04:04:31

BurntPizza (157 views)
2014-04-08 23:06:04

tom_mai78101 (252 views)
2014-04-05 13:34:39

trollwarrior1 (207 views)
2014-04-04 12:06:45

CJLetsGame (214 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!