Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (121)
games submitted by our members
Games in WIP (577)
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  
  Loading a Bufferedimage  (Read 1813 times)
0 Members and 1 Guest are viewing this topic.
Offline oysterman

Senior Newbie





« Posted 2013-08-17 14:53:20 »

Greetings.

I seem to be having trouble loading a BufferedImage as a Class folder.
Essentially, I have these pieces of code in my ArtResources class :


   
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
public static Bitmap walltest = loadBitmap("/focus/Resources/textures/walltest.png");


   
   public static Bitmap loadBitmap(String filename){
      try {
         System.out.println(System.getProperty("java.class.path"));
         BufferedImage image = ImageIO.read(ArtResources.class.getResource((filename)));
      etc.
}


According to the getProperty() line, my class path is : D:\(...)\TimeStrips\bin

My resources are in a /src/Resources/textures folder. What am I doing wrong exactly ? No matter what path I specify, and which folder in the hierarchy I set as Class folder still yields me a java.lang.IllegalArgumentException: input == null! error.
Offline BurntPizza
« Reply #1 - Posted 2013-08-17 16:07:38 »

To access resources from a folder that is alongside the top sources package, use this:
ArtResources.class.getClassLoader().getResourceAsStream(filename);


Where filename =
"resources/textures/walltest.png"


This worked for me in a quick test in NetBeans, including when exported as a Jar.

Capitalize folders, etc. as you see fit.

(Directory structure I used:)
TimeStrips
   src
      focus
         ArtResources.java
      resouces
         textures
            walltest.png

For more info: StackOverflow
Offline oysterman

Senior Newbie





« Reply #2 - Posted 2013-08-25 10:39:47 »

[Edit] : Problem solved. Sorry for the unnecessary post.

/*Hmm. In the end I stuck with the class.getResource() method. It worked fine, I even added some .wav files for good measure, until I tried to export. And then, nothing, when the .jar is run, an unsized frame starts and that's it. I guess the resources aren't included, and in fact, the .jar only contains the .class files, no images, no sounds.

I tried implementing your method instead, with separate images and sounds folders, as I thought the files would then be added on  export, but it fails to load the sounds. I'm guessing that I'm unable to reset the classpath after having loaded images, and that it's trying to load sounds starting from the images folder.

I don't mind which method I use, but I'd like a properly running .jar. Sorry, looks like I'll need a bit more help on this one.*/
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline oysterman

Senior Newbie





« Reply #3 - Posted 2013-08-28 20:29:09 »

Actually, I have another question (sorry) : is the relative filepath I provided above valid for all platforms ?

I exported a .jar recently and it seemed to work on mac and windows distributions, but linux distributions wouldn't load images and sounds ? Somebody suggested I change the first '/' to './' but that didn't change anything.

I've done a bit of searching, and though there are some topics on similar matters, none seem to focus on this particular aspect of exports, to my knowledge.
Offline Several Kilo-Bytes

Senior Duke


Medals: 11



« Reply #4 - Posted 2013-08-28 20:42:27 »

Jar resources are located using URLs not file names. They are part of a package, not a folder. The resource URLs' root is the unnamed default package, so it is better to use absolute paths starting with "/" than a relative path. (Again, it is a URL within your project, not a URL within the entire hard drive.) The resources can go in the same place as your source code in your IDE. The capitalization must be correct. The URL should be in the form "/firstpackage/secondpackage/third/fourth/no/real/project/has/this/many/subpackages/filename.extension". Package names should be all lower case just because that is convention. The capitalization of the resource name does not matter as long as it matches.

If you want a better answer you should post the error message, values of variables during execution (use println or a debugger), and the source code.
Offline oysterman

Senior Newbie





« Reply #5 - Posted 2013-08-29 14:04:14 »

Unless I'm mistaken, the method above uses URLs, I just confusingly call my variable 'filename'.

The piece of code that seems to be the problem is the one in my first post (and a similar bit for sounds).

My files are located in the /bin folder, in two separate folders, images and sounds. The .class files are in /bin/seconds/focus.

When I export and manually add the files in separate folders beside the .jar, it runs fine -except on Linux distributions, where I get this error, which leads me to believe the files aren't detected :

Exception in thread "main" java.lang.ExceptionInInitializerError
(...)
Caused by: java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at seconds.focus.gui.Images.loadBitmap(Images.java:36)
at seconds.focus.gui.Images.<clinit>(Images.java:13)

I'm probably not doing something right here, but if I add the files to the .src folder and export them, they appear in the .jar but still don't seem to be detected, which is strange...
Offline davidc
« Reply #6 - Posted 2013-08-29 15:01:03 »

What is the exact value of this "filename" variable and the exact location of the file within the jar. Note the emphasis on exact. Cut and paste the path if required so we get the correct capitalization, this is no time for vagueness.
Offline jonjava
« Reply #7 - Posted 2013-08-29 15:05:52 »

http://www.java-gaming.org/topics/having-an-issue-loading-text-files/30433/msg/281026/view.html#msg281026

Offline oysterman

Senior Newbie





« Reply #8 - Posted 2013-08-29 18:02:31 »

filename is (in the case of the first image I load) : /images/title.png
(I changed layouts and names some)

Layout is like this :

bin
   images
      title.png
      ...
   seconds
      focus
         gui
            Display.class (contains main)
            Images (loads Bitmaps)
            Sound (loads sounds)
   sounds
      ...


When I export it as is, the images and sounds folders aren't added to the .jar. So I add them and place them next to the .jar. Then everything works fine, except on Linux (why it doesn't work I don't understand). I would like it to work on Linux.

I hope this is clear enough.
Offline jonjava
« Reply #9 - Posted 2013-08-29 18:32:08 »

I don't just link topics for shits and giggles you know. Although the link directs you to my post since I just copy pasted it from my history - the idea is to read the whole topic to understand the context.

There's a difference between class.getResource() and class.getClassLoader().getResource().

If you'd bother to read the topic and think for a second you might, god forbid, actually learn something.

http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource
http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Several Kilo-Bytes

Senior Duke


Medals: 11



« Reply #10 - Posted 2013-08-29 18:37:01 »

The resources can go in the same place as your source code in your IDE.

You shouldn't ever need to touch anything inside the bin folder yourself.

Resources go in the src folder or they won't get put in the jar.
Offline jonjava
« Reply #11 - Posted 2013-08-29 18:48:52 »

The resources can go in the same place as your source code in your IDE.

You shouldn't ever need to touch anything inside the bin folder yourself.

Resources go in the src folder or they won't get put in the jar.

I suggest you go ahead and read the topic as well.

Offline philfrei
« Reply #12 - Posted 2013-08-29 18:53:53 »

I'm curious what you mean by ".. the images and sounds folders aren't added to the .jar. So I add them .."

Are you using Eclipse? Both source code and resources should be in a subfolder to src (if you are using Eclipse).[EDIT: corrected thanks to jonjova's note below.]

If you use "Export" "Jar file" (not "Runnable JAR file") then the screen "Jar File Specification" comes up with an expandable directory tree. If the folder with the resources is not clicked, you can select it at that stage. Maybe that is what you are already doing. Just confirming.

I found this section of the java tutorials helpful, even though it mostly talks about loading images for Icons. It has examples of several different loading scenarios:
see: Loading Images Using getResource
http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

"It's after the end of the world! Don't you know that yet?"
Offline oysterman

Senior Newbie





« Reply #13 - Posted 2013-08-29 19:34:30 »

My apologies, jonjava, but I was answering davidc's question.

And I have looked at the first topic you mentioned (but not all the others -yet). However, it does not seem to answer my question regarding Linux builds and why my method works EXCEPT for Linux builds.

I am looking more into the topics right now. Sorry if I've unintentionally annoyed you.
Offline jonjava
« Reply #14 - Posted 2013-08-29 20:05:05 »

From your OP it looks like you're using class.getResource() as opposed to getClassLoader().getResource() and considering your reply to davidc you're using a forward slash at the beginning of your filename:



Now if you take a look at what it says on the class.getResource() API (and how it significantly differs from getClassLoader().getResource()) you will notice this:



Basically you're probably using absolute paths which is never good. You want to use relative paths that encapsulate OS differences.
http://en.wikipedia.org/wiki/Path_(computing)

Also, having stuff inside the 'src' directory is in no way a prerequisite of having your resources exported inside a jar file.

Offline oysterman

Senior Newbie





« Reply #15 - Posted 2013-08-29 20:27:43 »

All right. So using this new structure, taking inspiration from your other topic :

bin
res
   sounds
      explosion.wav
   images
      title.png
src

public static Bitmap title = loadBitmap("title.png");

with loadBitmap containing :
BufferedImage img = ImageIO.read(Images.class.getClassLoader().getResourceAsStream(filename));

This is a relative path, yes ?

It works fine for images, which is nice.
However, it fails to do so for sounds afterwards, and I don't understand why :


public static Sound shoot = loadSound("shoot.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream((Sound.class.getClassLoader().getResourceAsStream(filename)));

[Edit] : Something I'd forgotten to mention : I hadn't added my res folder to the build path as a source folder. However, when I did so, images stopped working. Removing the folder from the build path didn't start making the images load properly as before, so there's some otehr subtlety going on I don't know about, apparently.
Offline Several Kilo-Bytes

Senior Duke


Medals: 11



« Reply #16 - Posted 2013-08-29 20:37:00 »

I suggest you go ahead and read the topic as well.

Also, having stuff inside the 'src' directory is in no way a prerequisite of having your resources exported inside a jar file.

Normally I try to be as precise as possible. This time I said "the src folder" because I thought "a source folder" would be a little too complicated in this context. persecutioncomplex

However I did find out that ClassLoader's getResource does not treat paths correctly (the leading / must be omitted).

I would recommend using absolute paths for resources because you want to uniquely identify a resource and you control the absolute path to your resource. (Unlike filesystems.) Its simpler if you use absolute paths so you wont have to move resources with your source code or fix a path every time if it happens to get passed between code in different packages.
Offline Several Kilo-Bytes

Senior Duke


Medals: 11



« Reply #17 - Posted 2013-08-29 20:47:52 »

BufferedImage img = ImageIO.read(Images.class.getClassLoader().getResourceAsStream(filename));

This is a relative path, yes ?

No it is absolute because of the way ClassLoader works...

Quote
It works fine for images, which is nice.
However, it fails to do so for sounds afterwards, and I don't understand why

[Edit] : Something I'd forgotten to mention : I hadn't added my res folder to the build path as a source folder. However, when I did so, images stopped working. Removing the folder from the build path didn't start making the images load properly as before, so there's some otehr subtlety going on I don't know about, apparently.

It should not have worked in the first place. Are you sure you are not using files? Or did you put res inside the src folder and then try to add res as a source folder?
Offline oysterman

Senior Newbie





« Reply #18 - Posted 2013-08-29 20:57:38 »

My bad, the images were also stored elsewhere.
Anyways, I'm pretty tired right now. I'll read up more on it tomorrow and hopefully be able to work things out a bit more than I am right now. Thank you for your help, anyway, all of you.
Offline jonjava
« Reply #19 - Posted 2013-08-29 23:28:02 »

http://www.java-gaming.org/user-generated-content/members/54159/frogs.jar

Works for me on windows and linux.



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  
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {

   BufferedImage image;
   Clip clip;

   public Main() {
   }

   private void load() {
      System.out.print("Loading image... ");
      try {
         URL url = this.getClass().getClassLoader()
               .getResource("art/eastwood.jpg");
         image = ImageIO.read(url);
         System.out.println("Success.");
      } catch (Exception e) {
         System.out.println("Failed.");
      }

      System.out.print("Loading sound... ");
      try {
         URL url = this.getClass().getClassLoader()
               .getResource("snd/water-flowing.aif");
         clip = AudioSystem.getClip();
         AudioInputStream ais = AudioSystem.getAudioInputStream(url);
         clip.open(ais);
         System.out.println("Success.");
      } catch (Exception e) {
         System.out.println("Failed.");
      }
   }

   private void show() {
      JFrame frame = new JFrame("Frogs");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setResizable(false);

      ImageIcon icon = new ImageIcon(image);
      JLabel label = new JLabel(icon);

      frame.add(label);

      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

      clip.loop(-1);
   }
   
   private void close() {
      clip.close();
   }

   public static void main(String[] args) {
      Main m = new Main();
      m.load();

      try {
         m.show();
         Thread.sleep(10*1000);
      } catch (Exception e) {
         System.out.println("Headless Mode Exception.");
      }
      m.close();
      System.exit(0);
      System.out.println("Closing.");
   }
}

Offline oysterman

Senior Newbie





« Reply #20 - Posted 2013-08-29 23:53:13 »

Wow. You didn't need to go so far as to spend some time making an example. But thanks a bunch for the help.

[Edit] : Success. I get a proper .jar, it seems. I had to clean up another issue with sounds, but it works. Phew. Sorry for being such a blockhead, anyway.
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.

theagentd (18 views)
2014-10-25 15:46:29

Longarmx (52 views)
2014-10-17 03:59:02

Norakomi (45 views)
2014-10-16 15:22:06

Norakomi (34 views)
2014-10-16 15:20:20

lcass (39 views)
2014-10-15 16:18:58

TehJavaDev (68 views)
2014-10-14 00:39:48

TehJavaDev (68 views)
2014-10-14 00:35:47

TehJavaDev (60 views)
2014-10-14 00:32:37

BurntPizza (74 views)
2014-10-11 23:24:42

BurntPizza (45 views)
2014-10-11 23:10:45
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
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!