Reading external images - java

I've looked around and have tried many fixes, but I can't seem to find one that works.
I'm making a simple frogger game, and I originally had all of my sprites loaded in the project directory like img/spritename.png:
image = ImageIO.read(getClass().getResourceAsStream("img/map.png"));
or
ImageIO.read(getClass().getResource(sprite));
Everything worked fine and dandy, but I went to move all of my images to an external directory so I can create an installer for it.
"C:\Program Files\DIR\img\" and all of the sprites no longer load.
The code I thought would fix it but didn't
BufferedImage image = null;
File dir = new File(Config.imgDir + "map.png");
try {
image = ImageIO.read(dir);
} catch (IOException e) {
e.printStackTrace();
}
if (image == null) {
return;
}
}
Config code:
public static String imgDir = "C:/Program Files/EmulousSoft/Frogger/img/";
Does anyone have any ideas? I'm sure it's simple, but every time I try different methods, I get "Value cannot be a null", "cannot find directory" or this.

Related

File as a executable jar file - sound / pictures don't work with gui button(s)

Yes I have researched online stackflow I believe was one place. And they have questions that "sound / audio" and i believe also "pictures" dont play from executable jar file.
The wav files are in the jar file...i used winrar to check.
I ran from the command prompt, and the sound wouldnt play. And one of the errors that was given was that :
java.io.FileNotFoundException : C:\Users\Bijan\Desktop\Sounds\SexySounds1.wav (The system can not find the path specified)
etc...I have another thing to add. That the pictures actually do work on the button when only pictures are used from executable jar file, but audio doesn't seem to play when I try to use a button that implements audio (wav) files.
This code below sets opt for JOptionPane, and I just put the images inside that box, and the audio (wav) files. This below code is for the button "Relax" for the gui program.
JButton btnNewButton_1 = new JButton("Relax");
btnNewButton_1.addActionListener(new ActionListener() {
private int counter = 0;
public void actionPerformed(ActionEvent e) {
String soundName1 = "Sounds/SexySounds1.wav";
String soundName1a = "Sounds/SexySounds2a.wav";
String soundName2 = "Sounds/HoShit.wav";
String soundName3 = "Sounds/SexySounds2.wav";
AudioInputStream audioInputStream = null;
JOptionPane opt = new JOptionPane("");
opt.setPreferredSize(new Dimension(210, 325));
final JDialog dialogBoxTitle = opt.createDialog("Sexy Woman");
try{
if(counter == 0){
Image pic = new ImageIcon(this.getClass().getResource("/SexyWoman.png")).getImage();
opt.setIcon(new ImageIcon(pic));
audioInputStream = AudioSystem.getAudioInputStream(new File(soundName1).getAbsoluteFile());
}
if(counter == 1){
Image pic = new ImageIcon(this.getClass().getResource("/Sexy Woman #2.jpeg")).getImage();
opt.setIcon(new ImageIcon(pic));
audioInputStream = AudioSystem.getAudioInputStream(new File(soundName2).getAbsoluteFile());
try {
Thread.sleep(500L);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
if(counter == 2){
Image pic = new ImageIcon(this.getClass().getResource("/SexyWoman#3.jpeg")).getImage();
opt.setIcon(new ImageIcon(pic));
audioInputStream = AudioSystem.getAudioInputStream(new File(soundName1a).getAbsoluteFile());
}
if(counter == 3){
Image pic = new ImageIcon(this.getClass().getResource("/SexyWoman#4.jpeg")).getImage();
opt.setIcon(new ImageIcon(pic));
audioInputStream = AudioSystem.getAudioInputStream(new File(soundName3).getAbsoluteFile());
}
if(counter == 4){
Image pic = new ImageIcon(this.getClass().getResource("/Bijan's Picture.png")).getImage();
opt.setIcon(new ImageIcon(pic));
}} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Clip clip = null;
try {
clip = AudioSystem.getClip();
} catch (LineUnavailableException e1) {
e1.printStackTrace();
}
try {
clip.open(audioInputStream);
} catch (LineUnavailableException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
clip.start();
counter++;
new Thread(new Runnable()
{
public void run()
{
try{
Thread.sleep(1500);
}catch (InterruptedException e) {
e.printStackTrace();
}}}).start();
dialogBoxTitle.setVisible(true);
}
}
);
Bijan
PS : I wanted to truly see if the wav files were in the jar file, and when I run the command prompt :
java -jar "SuperMathBattler1a.jar" the program runs. Yet when I try to view contents of the jar file using :
jar tf SuperMathBattler1a.jar
Then it gives this error :
'jar' is not recognized as an internal or external command, operable program or batch file.
I researched and what was written was that I have to alter the "PATH" yet that doesnt make sense since when I run it it works, so the path should be correct right? There maybe is something really fu--ed with this computer. I run from command prompt with :
C:\Users\Bijan\Desktop>
and I enter jar tf filename.jar
jar file is in desktop folder, yet doesnt view contents of jar file, yet runs it when I input --- java -jar "filename.jar"
I'm a beginner in java myself. Made a GUI an executable .jar. I had the same problem you have. My GUI has different pics for different listeners and a .wav for one. My executable .jar wouldn't show or play them. What no one told me, and I found out by just making an assumption. The jar is only "saving" the paths to those files, but the files themselves must still be included into the same folder as the jar file. If ever they are separated the jar will execute without them.
Example:
I made the original .jar in the original class folder I ran everything from in JCreator. The .jar runs as intended because all the pics and the .wav were in that folder.
I copy and pasted the .jar to a new folder exclusively for itself on my desktop. Clicked it to run, and it ran without the pics or the wav.
I copy and pasted the pics and .wav to that same .jar exclusive folder and it ran exactly as I intended pics, music, and all.
One cool thing I learned from that as a beginner in java is that I can create a generically titled file path, but use different pics in different .jar folders to make the .jar customable.
Example:
To the same aforementioned .jar I added a listener to set a friends face pic on the gui after log in.
The path in the code has
friendsPic =new imageIcon("friend.jpg").
In my listener for "Log In" I added If(logIn.equals("Sarah")||logIn.equals("Deena")) then add friendsPic to panel.
The difference is, I made a .jar with this code. I duplicated the .jar into two seperate folders. One I want to send to my friend Deena, the other for Sarah. Deena's folder has the .jar and a .jpg of her title "friend". Sarah's folder has the exact same .jar as well as a .jpg of her titled "friend". The .jar doesn't know the difference between the pics just that it has a path to a file labeled friend. I can run both .jars from there respective folders. Because Deena's folder has Deena's pic labeled friend, her jar displays her pic. Because Sarah's folder has her pic labeled friend, her jar displays her pic.
I hope this helps even if it wasnt the precise answer a more experienced programmer could have given.

Java BufferedImage throwing NullPointerException

I am making a space shooter in Java, but when I try to load up the image resources, I get a null pointer exception. Everything works fine except the images. Am I coding the directory wrong? How can I fix it?
Here is my code:
BufferedReader highScoreReader;
BufferedWriter highScoreWriter;
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/enemy.png"));
highScoreReader = new BufferedReader(new FileReader("/files/HIGH_SCORE.txt"));
highScoreWriter = new BufferedWriter(new FileWriter("/files/HIGH_SCORE.txt"));
} catch (Exception e) {
e.printStackTrace();
}
Here is a screenshot of my file directories:
Most probably, you need to copy your images into the build directory of your project. If you want them treated as classpath resources, which it seems you do, make sure they're in a source folder in eclipse (or, if you use maven or similar, in the src/main/resources folder. The point is, they need to be copied to the place where the .class file lives when it's running.
Remember: class.getResourceAsStream(...) returns things from the classpath not from your source path.
I've never seen it done that way.
Try this
try {
playerImage = ImageIO.read(getClass().getClassLoader().getResourceAsStream("src/res/player.png"));
catch(IOException e) {
}
or
try {
playerImage = ImageIO.read(new File("src/res/player.png"));
catch (IOException e) {
}
Arnav Garg has discovered the problem.
When your code says something like:
file("src/res/player.png")
the file is not there, i.e.
file.exists()
will return false
Find out where java thinks the file is.
try using
file.getAbsolutePath()
and compare that to your directory structure.

How to Read a File From Any Computer (Java)

Currently I have code like this in my program:
BufferedImage ReadPicture = null;
try {
ReadPicture = ImageIO.read(new File("C:/Users/John/Documents/NetBeansProjects/Program5/build/classes/Program5/Pictures/TestPicture.png"));
} catch (IOException e) {
}
If I compile my file to a jar and give it to someone else, the program does not work as the classpath is specific to my computer. How can I change how I access files/images so that it works on all computers?
For ImageIO in particular, if you always want to read an image from the classpath, without regard to what the classpath actually is, then you can do this:
BufferedImage readPicture = null;
URL imageUrl = getClass().getClassLoader().getResource(
"/Program5/files/Pictures/TestPicture.png");
// Or
// InputStream imageStream = getClass().getClassLoader().getResourceAsStream(
// "/Program5/files/Pictures/TestPicture.png");
// null if not found
try {
readPicture = ImageIO.read(imageUrl);
// null if the image format is unrecognized
} catch (IOException e) {
// ...
}
That relies on the fact that ImageIO can obtain images via URLs. This approach can be used even if the image is packaged in a Jar file, along side your classes (or not).
You can add a folder in your project named files or anything you want.You can make sub-directories in it and arrange files in that.They will be available when you will share it with others.In the code below,"." represents working directory.So make sure the directory structure you are providing,is correct.Try something like this.
BufferedImage ReadPicture = null;
try {
ReadPicture = ImageIO.read(new File("./files/Pictures/TestPicture.png"));
} catch (IOException e) {
}
See Also
Java Project Folder Structure

FIle saving path

I have created code that makes print screens and saves them as an imiage, but I don't really know how to change the path of saving the file for other folder in my main project folder. Any ideas?
private static void print(JPanel comp, String nazwa) {
// Create a `BufferedImage` and create the its `Graphics`
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(comp.getWidth(), comp.getHeight());
Graphics graphics = image.createGraphics();
// Print to BufferedImage
comp.paint(graphics);
graphics.dispose();
// Output the `BufferedImage` via `ImageIO`
try {
ImageIO.write(image, "png", new File(nazwa+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
Write the full path in the File constructor:
new File("/home/cipek/images/filename.png")
However I have still got a problem. I am not sure that udnerstand it properly.
cipek- is my project name
images- folder where i want to keep images
But what about home?? I rewrite "home" however it doesn't work.I don't want to give whole path because I will use this proram on other computers so the path will be diffrent every time.

Java input == null why?

I'm using a simple way to get my resources for the project. I'm using Eclipse, and I have a 'res' folder to hold the needed files. This is how I load stuff, for example a 'puppy.png' just in my res folder (no subfolders):
String path = "/puppy.png";
try {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
} catch(Exception ex) { ex.printStackTrace(); }
And sometimes I get an input==null error, and sometiomes not! Not like this time puppy.png loaded but next time it won't. For some classes it always loads correctly, and for the other classes I always get this error. Can anyone explain why can this happen, and how can I fix it, but still use the getResourceAsStream() method?
Please have a look at How to retrieve image from project folder?.
I have mentioned no of ways to read image from different paths.
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
In your case the image must be in the same package where is the class and don't prefix /.
Note that if the resource returns null (meaning it doesn't exist), you will get this error.
Check the input returned like so:
String path = "/puppy.png";
try {
InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
//resource doesn't exist
} else {
BufferedImage image = ImageIO.read(is);
}
} catch(Exception ex) { ex.printStackTrace(); }
Note that you most likely should be using String path = "puppy.png", seeing as you will already be in the content of the project folder.

Categories