Problem loading image (from JAR)

Hi
I was wondering why this code works when running the app in my IDE, but not once exported in a JAR file:
public static BufferedImage loadDefaultCover()
          try
               return ImageIO.read(new File("./images/default.png"));
          }catch(IOException e)
               logger.severe("Failed loading default img: "+e.getMessage());
          return null;
     }     NOTE 1: The cover is located (project root)/images/default.png
NOTE 2: It works when I have a folder named images (with the image in it) next to the JAR.
NOTE 3: I tried:
return ImageIO.read(new File("images/default.png"));
return ImageIO.read(new File("/images/default.png"));Any ideas? Thanks!
Andrew
Edited by: Andrew_ on Jan 4, 2009 12:45 PM

You can't use File references to access resources in a jar file (technically, they are not presen in the file system but part of a zip file). Instead, you can load those resources via the classloader:
return ImageIO.read(getClass().getClassLoader().getResourceAsStream("images/default.png"));

Similar Messages

  • Problem loading image from jar file referenced by jar file

    First, I searched this one and no, I didn't find an answer. Loading images from jar files has been pretty much done to death but my problem is different. Please read on.
    I have my application, a straight up executable running from Eclipse. It uses a jar file, call it JarA. JarA launches a GUI that is located in another jar file. Call it JarB. To recap:
    My application calls JarA -> JarA loads classes from JarB -> JarB looks for images to place in a GUI it wants to show on the screen
    When JarB goes to load an image the following happens:
    java.lang.NullPointerException
         at sun.misc.URLClassPath$3.run(URLClassPath.java:316)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:313)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:290)
         at sun.misc.URLClassPath.findResource(URLClassPath.java:141)
         at java.net.URLClassLoader$2.run(URLClassLoader.java:362)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findResource(URLClassLoader.java:359)
         at java.lang.ClassLoader.getResource(ClassLoader.java:977)
         at org.cubrc.gmshell.gui.MainWin.preInit(MainWin.java:152)
         at org.cubrc.gmshell.gui.MainWin.<init>(MainWin.java:135)
    The code from JarB that loads the image looks like this:
              URL[] oSearch = {Main.class.getResource("images/")};
              URLClassLoader oLoader = new URLClassLoader(oSearch);
              imgIcon = new ImageIcon(oLoader.getResource("icon.gif"));
              imgMatchRunning = new ImageIcon(oLoader.getResource("gears.gif"));
              imgMatchStill = new ImageIcon(oLoader.getResource("gears-still.gif"));
              imgMagnify = new ImageIcon(oLoader.getResource("magnify.gif"));This looks right to me and JarB certainly has an images directory with those files. But I'm in hell right now because I don't know where to place the images to make this work or if you can even attempt to load images with a dependency chain like this.
    Any help very appreciated!

    Have you tried to move your image-files out of the jar file and place them in the sam folder as the jar-file? I think that would help.
    When you try to load the image-file you get the NullPointerException because the program tries to read a file it can't find. Remember that a jar file IS a file and not a directory.
    If you want to read somthing inside the jar-file you need to encode it first.
    Have you tried to read the jar-file with winRar. It makes it easy to add and remove files in your jar-file.

  • Please have a look at this, problem loading images from jar.

    I made a post at the wrong place..
    Pleae have a look at it:
    http://forum.java.sun.com/thread.jsp?forum=422&thread=434524&tstart=0&trange=15

    Answer (hopefully not totally useless) posted over there.

  • Loading image from jars only once in oracle forms 10g

    Hi,
    I have an oracle forms 10g application which loads image from a jar. Every time i click on a button "A" that loads the image "image" on another button "B" in the same screen, a message is displayed in the java console "Loaded image: jar:https://+IP+/forms/java/+myjar+.jar!/image.gif". So after 10 clicks, i get the same message displayed 10 times. In the form, i've called:
    SET_CUSTOM_PROPERTY(p_object_name, 1, 'IMAGE_NAME_ON', '/'||p_image_name);My question is the following:
    - is there a way to load this image once and use it later without having to load it every time i clik on "A"? if yes, how?
    P.S.: if this thread shouldn't be posted in this forum, please redirect me to the right one.
    Thanks in advance

    Ah okay.
    I'm using the rolloverbutton.jar (RollOver Button PJC) [RolloverButton.java -> authors: Steve Button, Duncan Mills].
    Here is the part concerning the IMAGE_NAME_ON function:
    // make sure we are in rollover mode
    enableRollover();
    log("setProperty - IMAGE_NAME_ON value=" + value.toString());
    // load the requested image
    m_imageNameOn = (String) value;
    loadImage(ON,m_imageNameOn);
    // reset the currrently drawn image if needed
    setImage(ON,m_state);
    return true;where loadImage function is:
        URL imageURL = null;
        boolean loadSuccess = false;
        //JAR
        log("Searching JAR for " + imageName);
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          log("URL: " + imageURL.toString());
          try
            m_images[which] = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            log("Image found: " + imageURL.toString());
          catch (Exception ilex)
            log("Error loading image from JAR: " + ilex.toString());
        else
          log("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          log("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
              log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          log("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
                    log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          log("Error image " + imageName + " could not be located");In this case, what shall i modify?
    Thanks in advance

  • Problem loading images from a return value of a function

    hello, I write because I uin problem in loading images from a return value of a function.
    I created a database with a field "image" of type string, where I put the physical address of the image. I have written like this: {__DIR__ }foto.jpg
    Place the code, so you understand better
    function imageViewImage(): javafx.scene.image.Image {
    connetti();
    lass.forName(driverName);
    con = DriverManager.getConnection(url,user,"");
    stmt = con.createStatement();
    var richiesta:String = "SELECT image from viaggio WHERE id_viaggio=7";
    rs1 = stmt.executeQuery(richiesta);
    var result :String;
    rs1.next();
    risultato = rs1.getString("image");
    JOptionPane.showMessageDialog(null, result);
    var imagez = Image{
    url:"{result}";
    return imagez;
    The image is in the source code package
    First I connect to the database, run the query and I take the contents of the image.
    Can anyone help me?
    Is right to put in the database {__DIR__} foto.jpg or do I put only foto.jpg?

    Hello unkus_nob,
    I would rather suggest you to save only filename of that image like "foto.jpg" in database. And just concat it with the String variable containing "{__DIR__}".
    Actually the javafx compiler converts the {__DIR__} to the existing class directory path something like : "jar:file:/..../".
    var currentDir ="{__DIR__}";
    risultato = "{currentDir}{rs1.getString("immagine"})"; 
    var image = Image{
        url:risultato
    return image;--NARAYAN G.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • PJC - Loading Images from JAR Files

    I'm developing a PJC class that involves loading images. I would like to be able to find and use an image contained in a JAR file just like the built-in Forms items do; not the JAR file where my class is contained but any external ones defined in the server archive settings.
    I have seen the loadImage method in the demo RolloverButton class but this only loads images from the class's JAR and not any others.
    Is there a VButton method or an Oracle loader class for finding image resources from the defined JAR archives? If not, could someone supply some code for achieving this.
    Thank you.

    Hi,
    the jar file name the images are in shouldn't matter for the code as long as the package name is preserved. If you want to see it with your own eyes, do the following
    1. Back up demo90.jar
    2. Create a copy of it and call it demo90img.jar
    3. Open demo90.jar in winzip and remove all images
    4. Open demo90img.jar and remove all Java classes
    5. add ,/forms90demo/jars/demo90img.jar to the archive_jini tag of a demo you want to test this on
    6. Run the application and see the images despite the fact they are now in a separate jar file. Note in the Jinitiator console that the new jar files are downloaded and replace the existing, cached, jars
    7. Run an application that doesn't have demo90img.jar configured to see that the images are missing.
    Frank

  • Loading images from jar

    Found a good solution that works from running in command line, i.e java -jar or normally or using web start and not getting missing image URL loading from jar
    It deserves some dukes :) Also, someone can improve on it to make sure it's 100%
    Asume the function is in a package AWTUtilities class
    Many forums provide close solution but they all forget the vital replacing back slash with forward slash when reading from jar!! :)
    That's what got me stump for a good day trying to figure why it should load the images, but it's not...
    Regards
    Abraham Khalil
       // The subtlety in getResource() is that it uses the
       // Class loader of the class used to get the rousource.
       // This means that if you want to load a resource from
       // your JAR file, then you better use a class in the
       // JAR file.
       public static Image getImageResource( String name ) throws java.io.IOException {
          return getImageResource( AWTUtilities.class, name );
       public static Image getImageResource(Class base, String name ) throws java.io.IOException {
          if (name != null) {
             Image result = null;
             // A must, else won't pick the path properly within the jar!!
             // For file system forward or backward slash is not an issue
             name = name.replace('\\', '/');
             // For loading from file system using getResource via base class
             URL imageURL = base.getResource( name );
             // For loading from jar starting from root path using getResource via base class
             if (imageURL == null) {
                imageURL = base.getResource("/" + name );
             // For loading from file system using getSystemResource
             if (imageURL == null) {
                imageURL = ClassLoader.getSystemResource( name );
             // For loading from jar starting from root path using getSystemResource
             if (imageURL == null) {
                imageURL = ClassLoader.getSystemResource("/" + name );
             // Found the image url? If so, create the image and return it...
             if ( imageURL != null ) {
                Toolkit tk = Toolkit.getDefaultToolkit();
                result = tk.createImage( (ImageProducer) imageURL.getContent() );
             return result;
          else {
             return null;

    The problem is that you use the wrong classloader. The system default classloader is the one that launched the webstart utility. It doesn't contain your classes or jars. You have to get hold of the classloader for your classes.
    Here's my solution as a schetch: probably it won't compile but you get the idea:
    // 1: get hold of the classloader for my classes:
    // - this class cannot possibly be loaded by anyone else:
    Object dummy = new Object(){
    public String toString() { return super.toString(); }
    ClassLoader cl = dummy.getClass().getClassLoader();
    // 2: get an inputstream to read resource from from jar:
    InputStream is = cl.getResourceAsStream("images/myimage.gif");
    // 3: create image from inputstream
    // can be done in many different ways using tmp-files etc.
    ImageIcon icon = new ImageIcon(is);
    Image img = icon.getImage();

  • Problem loading Applets from Jar files on 64 bit machine

    I am developing an applet (extends Applet but uses swing components) using JDK 1.6 (Though these problems still happen in JDK 1.7) and I am unable to get the applet to load on a 64 bit machine in most cases. The web server(s) are running on localhost and I am connecting on the same machine using a local network ip address (such as 192.168.*.*)
    Below are all of my test results. Can someone provide a suggestion for repairing this? The Windows Server machine is a clients computer I access to it via remote desktop but I can't do much with it though I do have administrator rights. The Windows 7 machine is my development platform so I have been able to do extensive testing on it.
    This problem is presenting in the following environments when trying to load an applet from JAR files in a HTML document using the Applet or Object tag.
    Windows Server 2008 (Intel Chipset)
    Tested Browsers:
    Internet Explorer 9 (32 bit) - Shows it is blocked by default then simply shows an x when loaded from a web page, same result when loading from local drive.
    Windows 7 Home Premium (AMD Chipset)
    Tested Browsers:
    Firefox 6.0.1 (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    Internet Explorer 9 (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    Internet Explorer 9 (64 bit) - Java logo shows with spinner and most of the windows desktop manager freezes, keyboard is the only thing that responds so you can alt-tab to another app to regain control of the desktop.
    Chrome (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    The only way I have been able to get a Java applet to run on a 64 bit machine are the following ways.
    Firefox 9 nightly (64 bit) works perfectly! Go Firefox!
    Internet Explorer 9 (32 bit) loading directly from drive (c:\...)
    Chrome (32 bit) loading directly from drive (c:\...)
    Firefox 6.0.1 (32 bit) loading directly from drive (c:\....)
    Can someone please help! I've been fighting with this bug for over a week and I can't find anything that will solve it, I have noticed that in some cases if my jar has very little code in it than it will run on the server, but the minute I start adding things to it the jar won't load anymore.

    jschell wrote:
    rritoch wrote:
    I am developing an applet (extends Applet but uses swing components) using JDK 1.6 (Though these problems still happen in JDK 1.7) and I am unable to get the applet to load on a 64 bit machine in most cases.
    To clarify...
    1. You have tried it on 32 bit machine? Exactly which OS?I tested this on Windows Vista Business which is in 32 bit mode and the applets run without any problems
    >
    2. Your only 64 bit tests have involved 2008/Win7?
    If so then I would suspect something with windows not java. Probably permissions.
    The web server(s) are running on localhost and I am connecting on the same machine using a local network ip address (such as 192.168.*.*)
    Yes, I haven't tried running the jars on other operating systems.
    >
    I don't understand that. If you are running on localhost then you should connect to localhost. If running on an IP then you should connect to that. Perhaps you meant that you have tested using both of those?I'm testing using the lan ip address but I'm connecting from the same machine. I've tried localhost and that didn't work so I tried lan ip since that will likely have a different java security context than localhost. At first I was blaming the IIS server but I downloaded the jar directly and using HTTP fox was able to verify that the jar is being sent with the correct mime-type and that the server can upload the jar file without a problem. This leaves me to believe the problem is with Java.

  • Loading images from jar file

    i use the instruction below to load image contained in my jar file for distribution application but the image doesn't appear
    icon = new ImageIcon("images/logo_tunisiana.GIF");
    the jar file contain the image under a subdirectory called images.
    Witch code sample have i to use ?
    thanks in advance

    I have an applet that is packaged in a jar file with images. I can access the images using:
    aIcon = new ImageIcon(KeyboardApplet.class.getResource("images/keyimages/a.jpg"));

  • Loading images from Jar - Please help!

    Tried with / in front of the path or without and using both
    getImageResource and getSystemImageResource methods and no images
    are showing.
    My jar has manifest file of:
    Main-Class: com.package.MainFrame
    Class-Path: j2ee.jar
    - blank line -
    Thanks
    Abraham Khalil
       // The subtlety in getResource() is that it uses the
       // Class loader of the class used to get the rousource.
       // This means that if you want to load a resource from
       // your JAR file, then you better use a class in the
       // JAR file.
       public static Image getImageResource( String name ) throws java.io.IOException {
          return getImageResource( AWTUtilities.class, name );
       public static Image getImageResource(Class base, String name ) throws java.io.IOException {
          Image result = null;
          URL imageURL = base.getResource( name );
          if (imageURL == null) {
             imageURL = base.getResource("/" + name );
          System.out.println("imageURL: " + imageURL + " AWTUtilities.class.getResource(" + name + ");");     
          if ( imageURL != null ) {
             Toolkit tk = Toolkit.getDefaultToolkit();
             result = tk.createImage( (ImageProducer) imageURL.getContent() );
          return result;
       public static Image getSystemImageResource( String name ) throws java.io.IOException {
          Image result = null;
          URL imageURL = ClassLoader.getSystemResource( name );
          if (imageURL == null) {
             imageURL = ClassLoader.getSystemResource("/" + name );
          System.out.println("imageURL: " + imageURL + " = ClassLoader.getSystemResource(" + name + ");");
          if ( imageURL != null ) {
             Toolkit tk = Toolkit.getDefaultToolkit();
             result = tk.createImage( (ImageProducer) imageURL.getContent() );
          return result;

    Hello,
    you must put your images files under your package :
    see full doc at this tutorial.
    Hope this helps,
    Neo

  • Why can I load Image from jar?

    hi,all:
    I've packed all gif images into a jar file,it works well on jdk1.4.2_05 with this command:
    java -jar pos.jar
    but failed on other jdk versions lower than jdk1.4.2_05.
    here is the package structure:
    &#9500;&#9472;resource
    &#9474; &#9500;&#9472;configfile
    &#9474; &#9492;&#9472;images
    here is the code getting url:
    package resource
    public class ResourceLoader {
    public ResourceLoader() {
    public URL getResource(String fileName){
    URL url=ResourceLoader.class.getResource(fileName);
    if(null==url){
    throw new NullPointerException(fileName+" not found");
    return url;
    with this url, I will use
    toolkit.getImage(url);
    to load the image.
    exception on 1.4.1_01:
    An unexpected exception has been detected in native code outside the VM.
    Unexpected Signal : EXCEPTION_ACCESS_VIOLATION occurred at PC=0x6D2835EB
    Function=JNI_OnLoad+0x249
    Library=C:\j2sdk1.4.1_01\jre\bin\jpeg.dll
    Current Java thread:
    at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
    at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:144
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.j
    ava:257)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:168)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    Dynamic libraries:
    0x00400000 - 0x00406000 C:\j2sdk1.4.1_01\bin\java.exe
    0x77F80000 - 0x77FFA000 C:\WINNT\system32\ntdll.dll
    0x77D90000 - 0x77DEB000 C:\WINNT\system32\ADVAPI32.dll
    0x77E60000 - 0x77F32000 C:\WINNT\system32\KERNEL32.dll
    0x786F0000 - 0x7875E000 C:\WINNT\system32\RPCRT4.dll
    0x78000000 - 0x78046000 C:\WINNT\system32\MSVCRT.dll
    0x6D330000 - 0x6D45A000 C:\j2sdk1.4.1_01\jre\bin\client\jvm.dll
    0x77DF0000 - 0x77E4F000 C:\WINNT\system32\USER32.dll
    0x77F40000 - 0x77F79000 C:\WINNT\system32\GDI32.dll
    0x77530000 - 0x77560000 C:\WINNT\system32\WINMM.dll
    0x75E00000 - 0x75E1A000 C:\WINNT\system32\IMM32.DLL
    0x6C330000 - 0x6C338000 C:\WINNT\system32\LPK.DLL
    0x65D20000 - 0x65D74000 C:\WINNT\system32\USP10.dll
    0x6D1D0000 - 0x6D1D7000 C:\j2sdk1.4.1_01\jre\bin\hpi.dll
    0x6D300000 - 0x6D30D000 C:\j2sdk1.4.1_01\jre\bin\verify.dll
    0x6D210000 - 0x6D229000 C:\j2sdk1.4.1_01\jre\bin\java.dll
    0x6D320000 - 0x6D32D000 C:\j2sdk1.4.1_01\jre\bin\zip.dll
    0x6D000000 - 0x6D0FB000 C:\j2sdk1.4.1_01\jre\bin\awt.dll
    0x777C0000 - 0x777DE000 C:\WINNT\system32\WINSPOOL.DRV
    0x75010000 - 0x75020000 C:\WINNT\system32\MPR.dll
    0x77A30000 - 0x77B1C000 C:\WINNT\system32\ole32.dll
    0x6D180000 - 0x6D1D0000 C:\j2sdk1.4.1_01\jre\bin\fontmanager.dll
    0x51000000 - 0x51044000 C:\WINNT\system32\ddraw.dll
    0x72800000 - 0x72806000 C:\WINNT\system32\DCIMAN32.dll
    0x72CF0000 - 0x72D63000 C:\WINNT\system32\D3DIM.DLL
    0x6DD30000 - 0x6DD36000 C:\WINNT\system32\INDICDLL.dll
    0x53000000 - 0x53007000 C:\PROGRA~1\3721\helper.dll
    0x70BD0000 - 0x70C34000 C:\WINNT\system32\SHLWAPI.dll
    0x37210000 - 0x3723E000 C:\WINNT\DOWNLO~1\CnsMin.dll
    0x777E0000 - 0x777E7000 C:\WINNT\system32\VERSION.dll
    0x75950000 - 0x75956000 C:\WINNT\system32\LZ32.DLL
    0x12F10000 - 0x12F25000 D:\JBuilder7\lib\ext\jbWheel.dll
    0x6D280000 - 0x6D29E000 C:\j2sdk1.4.1_01\jre\bin\jpeg.dll
    0x77900000 - 0x77923000 C:\WINNT\system32\imagehlp.dll
    0x72960000 - 0x7298D000 C:\WINNT\system32\DBGHELP.dll
    0x687E0000 - 0x687EB000 C:\WINNT\system32\PSAPI.DLL
    Local Time = Fri Jul 16 10:06:45 2004
    Elapsed Time = 2
    # The exception above was detected in native code outside the VM
    # Java VM: Java HotSpot(TM) Client VM (1.4.1_01-b01 mixed mode)
    # An error report file has been saved as hs_err_pid2320.log.
    # Please refer to the file for further information.

    help!!!!

  • Problem loading image from HTTPS

    I am having trouble loading an image in Java client , the image is coming from a secure server.
    My code looks as follows
    Image image = null;
    try
    // just substituting my image with the secure image I found on sun site
    URL url = new URL("https://www.sun.com/im/sun_logo.gif");
    image = getToolkit().getImage(url);
    catch(MalformedURLException e )
    System.err.println("invalid URL");
    if (image == null)
         System.err.println("null image");
    MediaTracker mediaTrack = new MediaTracker(this);
    try
         mediaTrack.addImage(image, 0);
         mediaTrack.waitForAll();
    } catch (InterruptedException ie)
    System.err.println("Interrupted Exception");
    if (mediaTrack.isErrorAny())
    System.err.println("Error loading the image");
    Initialy I got MalformedURLException but then I switched to jdk1.4.2 and set the following system property and got passed that part but now I am getting error when MediaTracker tries to load the image.
    System.getProperties().put("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
    I need to know if there is a better way of loading the image and if possible without having to set the system property.
    Thank you

    Have you tried using the HttpsURLConnection class introduced in JDK 1.4?

  • Problem loading URL from .jar file

    I encounter problems while loading a MsAccess DB contains within a .jar file. This is the following codes I used,
    try
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        java.net.URL url=getClass().getResource("MSAccessDB\\SavingApp DB.mdb");
        DBURL+=url.getFile();
    catch(Exception e)
    { System.err.println(e.toString()); }

    Could I ask that, if I stored the MsAccess or any other DBs, will the DB able to do basic operations (Create Update Retrieve Display)?
    As the DB is not like a normal Text file.
    What I did is that, I didn't include the MsAccess into the .jar file. I just put it beside. The disadvantage is that user ables to open the DB and might do some changes. ;-(

  • Loading resources from jar - problem

    I've got a problem when loading resources from jar.
    My code:
    package game.player;
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import game.map.Map;
    import game.map.MapReader;
    import game.emptyclass.EmptyClass;
    import java.net.URL;
    public class Data
        ClassLoader cl = EmptyClass.class.getClassLoader();
        Image image1 = new ImageIcon(cl.getResource("data/sprites/man6.png")).getImage();
        Image image2 = new ImageIcon(cl.getResource("data/sprites/man5.png")).getImage();
        Image image3 = new ImageIcon(cl.getResource("data/sprites/man4.png")).getImage();
        Image image4 = new ImageIcon(cl.getResource("data/sprites/man3.png")).getImage();
        Image image5 = new ImageIcon(cl.getResource("data/sprites/man2.png")).getImage();
        Image image6 = new ImageIcon(cl.getResource("data/sprites/man1.png")).getImage();
        public Image tile1 = new ImageIcon(cl.getResource("data/maps/test/tile1.png")).getImage();
        public Image bg = new ImageIcon(cl.getResource("data/maps/default/bg.png")).getImage();
        public Map map = new MapReader(cl.getResource("data/maps/test/test.map").getPath()).getMap();
        public int getImageWidth()
            return image1.getWidth(null);
        public int getImageHeight()
            return image1.getHeight(null);
    }I get a NullPointerException.
    Thanks in advance!

    Hi ,
    getResource() method argument is not begin with the
    character '/' , ex.
    Image image1 = new
    ImageIcon(cl.getResource("/data/sprites/man6.png")).ge
    tImage();
    I thought of that, but it's not applicable here because getResource is being called on the ClassLoader, not the Class.

  • Issues with Loading Images from a Jar File

    This code snippet basically loops through a jar of gifs and loads them into a hashmap to be used later. The images all load into the HashMap just fine, I tested and made sure their widths and heights were changing as well as the buffer size from gif to gif. The problem comes in when some of the images are loaded to be painted they are incomplete it looks as though part of the image came through but not all of it, while other images look just fine. The old way in which we loaded the graphics didn't involve getting them from a jar file. My question is, is this a common problem with loading images from a jar from an applet? For a while I had tried to approach the problem by getting the URL of the image in a jar and passing that into the toolkit and creating the image that way, I was unsuccessful in getting that to work.
    //app is the Japplet
    MediaTracker tracker = new MediaTracker(app);
    //jf represents the jar file obj, enum for looping through jar entries
    Enumeration e = jf.entries();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    //buffer for reading image stream
    byte buffer [];
    while(e.hasMoreElements())
    fileName = e.nextElement().toString();
    InputStream inputstream = jf.getInputStream(jf.getEntry(fileName));
    buffer = new byte[inputstream.available()];
    inputstream.read(buffer);
    currentIm = toolkit.createImage(buffer);
    tracker.addImage(currentIm, 0);
    tracker.waitForAll();
    images.put(fileName.substring(0, fileName.indexOf(".")), currentIm);
    } //while
    }//try
    catch(Exception e)
    e.printStackTrace();
    }

    compressed files are not the problem. It is just the problem of the read not returning all the bytes. Here is a working implementation:
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    try{
    byte[] buf = new byte[1024];
    int read;
    while((read = is.read(buf)) > 0) {
    os.write(buf, 0, read);
    catch(Exception e){
         e.printStackTrace();
         return null;
    image = Toolkit.getDefaultToolkit().createImage(os.toByteArray());
    This works but I think you end up opening the jar a second time and downloading it from the server again. Another way of getting the images is using the class loader:
    InputStream is = MyApplet.class.getResourceAsStream(strImageName);
    In this case, the image file needs to be at the same level than MyApplet.class but you don't get the benefit of enumerating of the images available in the jar.

Maybe you are looking for

  • Date format

    please take a look at this SQL statement: select date_column from table1 where to_char(date_column) = '00-000-00' btw i'm using oracle8.. if you use this statement in query analyzer it will return 01-JAN-99 but in sql woksheet it returns 00-000-00. h

  • How do I use 2 iPhones with one computer (iTunes)

    My wife & I each have an iPhone. Everytime I sync we both end up with the same songs, apps, etc. Is there a way that we can use the same computer for syncing but have our own separate libraries on our phones?

  • Filtering internal table using select-option values

    Hi, I got an internal table with select-option values. for eg.  it_perno with the values  I  BT    000160    000170. Now i got another second internal table which is have the person number. Now i need to filter this second internal table based on the

  • What to do with one 25i and one 25p file in same Timeline???

    Hey! I was bothering you with questions of how do I put 30p and 25i footage together, but things have changed. [i]HUNTREX and ANN BENS, thanx a bunch for your help)[/i] Canon released new Firmware for its 5D MkII camera, so I can shoot 25p and 24p...

  • Action Options (shortcut keys) disappear

    I'm setting up shortcut keys for actions on a new Mac Pro (the garbage can model). When I close photoshop then reopen it, the shortcuts are gone. The action is still there but the shortcut associated with it is gone. Any ideas? It's really that simpl