1

Below is the code that I am trying to use.

 InputStream in = new BufferedInputStream(Tester.class.getClassLoader().getResourceAsStream("appResources/img/GESS.png"));
 Image image=null;  
 try {
         image = ImageIO.read(in);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 System.out.println(image);

'image' comes null when I am printing it.

Yogesh Sanchihar
  • 1,080
  • 18
  • 25
  • Possible duplicate of [getResourceAsStream returns null](http://stackoverflow.com/questions/16570523/getresourceasstream-returns-null) – Antoine Apr 27 '17 at 07:52

4 Answers4

1

Try this:

InputStream in = Tester.class.getResourceAsStream("your/path");
Image image=null;  
try {
    image = ImageIO.read(in);
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(image);

The value or your/path is either appResources/img/GESS.png or /appResources/img/GESS.png depending on your maven configuration and the directory you setup for your project.

For instance, if you add the following entry to your pom.xml file:

<resources>
    <resource>
        <directory>src/main/appResources</directory>
    </resource>
</resources>

Then, you can get the same resource by using a shorter path since your program knows where to look for resources:

InputStream in = Tester.class.getResourceAsStream("img/GESS.png");
Image image=null;  
try {
    image = ImageIO.read(in);
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(image);

More info here and here.

Community
  • 1
  • 1
Antoine
  • 1,393
  • 4
  • 20
  • 26
0

you can use InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

G.Khandal
  • 44
  • 1
  • 3
0

you use like this InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

G.Khandal
  • 44
  • 1
  • 3
0

Here are two utility methods I'm using for image loading.

public static Image getImage(final String pathAndFileName) {
    try {
        return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
    } catch (final Exception e) {
        //logger.error(e);
        return null;
    }
}

public static URL getURL(final String pathAndFileName) {
    return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
01es
  • 5,362
  • 1
  • 31
  • 40