Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Trouble loading image as resource :(  RSS feed

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically still trying to learn Java and currently trying to load pics and sounds from my Jar file, and someone gave me a code snippet to try, but I'm unable to get it to work via Netbeans

Basically FileInputStream seems to be incompatible with getResourceAsStream (expecting fileInputstream not InputStream).

Plus how do I use the image - I've only used label.setIcon which doesn't like BufferedImage?!


// In this example, image.jpg must be in the same folder inside the JAR file as the class
FileInputStream in = getClass().getResourceAsStream("image.jpg");
// Use your favourite API (for example ImageIO) to load the image from the input stream
BufferedImage image = ImageIO.read(in);
// Close the stream
in.close();
picLabel.setIcon(image);
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just use InputStream. It will work fine.
 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, scratched together the code below which compiles, but picStream is returning null i.e. I get an exception on ImageIO that the stream is null

BTW there is definitley a folder DTImages in my class path i.e.
picLabel.setIcon(new ImageIcon("DTImages/beast.jpg"));
works fine.

I have also quadruple checked the case of resource and still no joy.

Any ideas?


InputStream picStream = getClass().getResourceAsStream("DTImages/beast.jpg"); //Also tried "DTImages/beast.jpg" but no joy
try {
final BufferedImage icon = ImageIO.read(picStream);
PlayPicViaThread(icon);
picStream.close();
}
catch (Exception e) {
e.printStackTrace();
};

P.S.
URL imgURL = getClass().getResource("DTImages/beast.jpg");
comes back null as well
[ March 02, 2007: Message edited by: Paul Carter ]
 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorted!

I guess my classpath wasn't where I thought it would be.
My pictures/soounds where in subfolders of my main project folder.

This worked fine for setImageIcon?!?!?

Anyway, found a subfolder buried away in the project folders somewhere called classes - moving the image/sound folders there made all the difference.

Many thanks guys.
 
Barry's not gonna like this. Barry's not gonna like this one bit. What is Barry's deal with tiny ads?
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!