I have scoured this site, and been looking over solutions on how to fix this, and none have given a solution that changes the error occurring. I cannot pinpoint what the problem is. None of the similar questions regarding this have helped.
I'll start with the code I have
public static BufferedImage getImage(String uri) throws IOException {
BufferedImage image = null;
image = ImageIO.read(ImageLoader.class.getResource(uri));
return image;
}
And where I call the method
try {
sprite = ImageLoader.getImage("images/testSprite.png");
} catch (IOException e) {
e.printStackTrace();
}
The error returned is IllegalArgumentException input == null on the ImageIo.read line in the original method.
To preface, I have tried every imaginable file naming sequence. I tried it including res, the name of my resource folder (both with and without a slash at the beginning), I tried it with a slash preceding images, the folder that contains the image I'm trying to access, and simply the name of the image, again, with and without the slash.
I used Eclipse's "Build Path" to create my res folder in the Project folder, but if I look at the .zip, it doesn't contain the folders I included, even the src folder, but it does contain all of the class files from the src folder. I'm confused why this is happening.
I would really like some insight on what exactly I am doing wrong here.
EDIT: After trying nearly everything imaginable, I finally figured it out. The folder needs to be created as a Package, and the image needs to be placed within the package. A source folder or normal folder doesn't seem to be picked up by the compiler. Just add a package to your source folder for the image to be loaded.
Related
I have explored every single solution related to this problem on Stack Overflow, and the solutions I encountered worked only in my IDE (Eclipse Mars), but when exported they all failed.
I have an image file I simply want to load from inside my exported jar.
As you can see from the project layout, Images is a folder directly inside of the project folder CooldownTrackerJava. To refer to it, I've tried a variety of methods.
//My class' name is AddItemDialog
//Method 1
String filePath = File.separator + "Images" + File.separator + "questionMark.png";
InputStream inputStream = AddItemDialog.class.getResourceAsStream(filePath);
BufferedImage img = ImageIO.read(inputStream);
I tried method 1 in a few ways. I tried it with and without the File.separator at the start of the filePath. I understand that the former refers to an absolute path, while the latter is relative. I also tried moving the Images folder inside of the directory where my class files were.
All of these failed giving me a NullPointerException when exported and tested multiple times.
//Method 2
String saveLocation = File.separator + "Images" + File.separator + "questionMark.png";
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(saveLocation));
As per this post I tried the above method however it still did not work.
I've tried many variations aside from the ones mentioned in this post but none of them have been successful when I exported the jar.
Do I need to add the Images folder to my build path? Should I move it to the src folder? Am I missing one obvious step? All suggestions would be highly appreciated. Also here is the layout of the exported jar file.
The solution was a two-part effort. Firstly, I moved my Images folder into the src directory as shown below. Kudos to Matthew.
I then removed File.separator and replaced it with a forward slash/. Thanks to fge.
Do not use File.separator(). Separators for resource paths on the class path is always /. If you use Windows you will therefore always get the wrong result.
I used a variant of method 1 to test it. Both methods will work though.
String saveLocation = "/Images/questionMark.png";
InputStream inputStream = this.getClass().getResourceAsStream(saveLocation);
try {
BufferedImage img = ImageIO.read(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to access some resources located in the top directory of my (Java) project (/resources/imgname.jpg) from a class 'GUI' located in a package 'gui'.
Originally I used the following code:
ImageIcon image = new ImageIcon("./resources/imgname.jpg");
Image img = image.getImage();
This works fine in Eclipse, but doesn't display the image when it's in a runnable JAR. So after some searching it seems you need:
InputStream resource = GUI.class.getResourceAsStream("./resources/imgname.jpg");
try {
Image image = ImageIO.read(resource);
} catch (IOException e) {//trycatch needed because of read method}
Now this doesn't work in either Eclipse or JAR.
I've tried changing reference and location, but the only way I can get the image to display is by placing it in the 'gui' package folder. So is there any way I can reference it in the top folder of the project instead (so I don't have to move the resources to 'gui')?
Thx,
Magic
Try this.
InputStream resource = GUI.class.getClassLoader().getResourceAsStream("resources/imgname.jpg");
It works for me.
I've seen many different examples showing how to set a JFrame's IconImage so that the application uses that icon instead of the standard coffee mug. None of them are working for me.
Here's "my" code (heavily borrowed from other posts and the internet at large):
public class MyApp extends JFrame
{
public MyApp()
{
ImageIcon myAppImage = loadIcon("myimage.jpg");
if(myAppImage != null)
setIconImage(myAppImage.getImage());
}
private ImageIcon loadIcon(String strPath)
{
URL imgURL = getResource(strPath);
if(imgURL != null)
return new ImageIcon(imgURL);
else
return null;
}
}
This code fails down in loadIcon when making a call to the getResource() method. To me, there's only 2 possibilities here: (1) the myImage.jpg is in the wrong directory, or (2) getResource() doesn't like something about my image (I had to convert it from CMYK to RGB in Photoshop so I could use the same image elsewhere with ImageIO.)
I have used the System.out.println(new File(".").getAbsolutePath()); trick to locate the directory where the image JPG should be stored, and still nothing worked. I have subsequently placed the JPG in just about every directory inside my project, just to rule file location out as the culprit.
So that leaves me to believe there's something that getResource() doesn't like about the JPG itself. But I have now already exhausted my understanding of images and icons in the mighty, wide world of Swing.
My JPG loads fine in other image viewers, so that's ruled out as well. Anyone have any ideas?
Thanks in advance!
I have tried following which was a answer for same kind of question like yours. And it works for me.
Try putting your images in a separate folder outside of your src
folder. Then, use ImageIO to load your images. (answered Aug 27 '13 at 0:18
AndyTechGuy)
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
put the image in the root of the classpath and say getResource("classpath:myimage.jpg");
The problem with your code is that jvm is unsure where to lookup the image file so its returning null.
Here is a nice link about classpath
It should be
if(imgURL != null)
^
instead of
if(imgURL !- null)
and
URL imgURL = this.getClass().getResource(strPath);
instead of
URL imgURL = getResource(strPath);
Then it works fine, if "myimage.jpg" is in the same dir with MyApp.class
Two suggestions:
Try using the getClass().getResource("x.jpg"), and putting the file directly in the same folder as the .class file of the class you are in.
Make sure the name is identical in case - some operating systems are case sensitive, and within a JAR, everything is case sensitive.
You can try to use a "/" before your filename.
getClass().getResource("/myimage.jpg")
If you look into your build-output folder (target) you can look for your class where you are trying to get your resource from.
Your resources will probably be copied in some folders above.
For example your target directory could look like this:
target
|- de.example.app
|- Main.class
|- Main-x.y.z.jar
|- myimage.jpg
So if you just go for getClass().getResource("myimage.jpg") it will look under the folder target/de/example/app and won't find a jpg there.
You need to tell him that you want to look under the root-folder (target/**). That's why you need to place a "/" before your file.
Looked at other posts on SO and they did not solve this issue.
I'm trying to load an image from my jar file. It is continuously coming up as null. The image is located under:
.Jar file > images > BLOCK.png
To load the image I am doing:
BufferedImage bImg;
URL url = getClass().getResource("/images/BLOCK.png");
try {
bImg = ImageIO.read(url);
} catch (IOException ex) {
Logger.getLogger(TileEngine.class.getName()).log(Level.SEVERE, null, ex);
}
url is null as is bImg.
Do not worry about case sensitivity as I've already checked that.
try this :
Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/BLOCK.png"));
Which jar file is the image in, compared with the class you're using to call getResource? If they're loaded by the same classloader, it should be fine.
Have you double-checked that the jar file actually contains the file?
Are you sure that your classloader is actually using the jar file at all (rather than .class files directly on disk, for example)?
If you have a short but complete program which demonstrates the problem, that would really help. (A console app would be ideal... we don't need to see the image, after all.)
I'm making a torpedo game for school in java with swing gui, please see the zipped source HERE.
I use custom button icons and mouse cursors of images stored in the /bin/resource/graphics/default folder's subfolders, where the root folder is the program's root folder (it will be the root in the final .jar as well I suppose) which apart from "bin" contains a "main" folder with all the classes. The relative path of the resources is stored in MapStruct.java's shipPath and mapPath variables.
Now Battlefield.java's PutPanel class finds them all right and sets up its buttons' icons fine, but every other class fail to get their icons, e.g. Table.java's setCursor, which should set the mouse cursor for all its elements for the selected ship's image or Field.java's this.button.setIcon(icon); in the constructor, which should set the icon for the buttons of the "water".
I watched with debug what happens, and the images stay null after loading, though the paths seem to be correct. I've also tried to write a test file in the image folder but the method returns a filenotfound exception. I've tried to get the path of the class to see if it runs from the supposed place and it seems it does, so I really can't find the problem now.
Could anyone please help me?
Thank you.
You need to load icons like this:
ClassLoader cl= this.getClass().getClassLoader();
URL imageURL = cl.getResource("resources/...");
ImageIcon icon = new ImageIcon(imageURL);
And you need to add your resource folder to the classpath in Eclipse. Note that the path is not a file path, this way it will work if you decide to bundle your app in a jar file.
btnRegistration.setIcon(createImageIcon("reg.png"));
protected ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Master.class.getClassLoader().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.out.println("Couldn't find file: " + path);
return null;
}
}
here btnRegistration is my JButton
Master is my Class
and reg.png is my image that is belong in my project