2D game ImageIO import issue [duplicate] - java

This is a question that has been asked like 100 times on this site, but I have looked at all of them and even though they all were solved, none of the solutions worked for me.
Here's what my code looks like:
public Button1(Client client, String imgName) {
this.client = client;
try {
this.icon = ImageIO.read(this.getClass().getResourceAsStream("/resources/" + imgName));
} catch (IOException e) {
e.printStackTrace();
}
When the code runs it results in the following error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
The string imgName is passed to the constructor from a child class and is the name of an image (e.g. image.png). I also have made sure that my resources folder is in the root of the project folder, and is included as a source folder in the eclipse project. I've also made sure that System.getProperty("user.dir") points to the correct location. I have also tried using getResource() instead of getResourceAsStream(), but it still does not work.

Try using this:-
this.icon = ImageIO.read(new FileInputStream("res/test.txt"));
where res folder is present at the same level as your src folder. Also, if you notice, the slash / before the res folder name was removed.

I know this is pretty old, but I just had the same issue.
Check to make sure that your image extensions aren't capital.
In my resources folder for images I had "enemy.PNG", but I was trying to load "enemy.png" which you would think would work but doesn't.
so, just make your extensions aren't capitalized.

I solved mine by changing my code from this
image = ImageIO.read(SpriteSheet.class.getResourceAsStream("res/image.png"));
to this
image = ImageIO.read(SpriteSheet.class.getResourceAsStream("/image.png"));
Hope this helps.

The path passed as the argument to getResourceAsStream() should be relative to the classpath set.
So try changing this
this.icon = ImageIO.read(this.getClass().getResourceAsStream("/resources/" + imgName));
to
this.icon = ImageIO.read(this.getClass().getResourceAsStream("resources/" + imgName));

This may come as a "No, Duh!" to many on this site, but it is always important to point out how literal Java is. Case sensitivity is key, especially if you .jar a file.
If your program works fine with compiling and then running but suddenly is getting this issue when you .jar your files. Make sure to check you Case on your folders / files and your references in your code. (As well as make sure they are in your .jar)
Hope this helps anyone that ends up here looking at the same issue.

Try this:
this.icon = ImageIO.read(this.getClass().getResource("/resources/" + imgName));

Try using the following
this.icon = ImageIO.read(this.getClass().getResourceAsStream("../resources/" + imgName));

Is the resource folder a class folder in eclipse? Right click on the project -> Properties -> Java Build Path -> Libraries -> Add Class Folder... -> (select the res folder) and add it as a class folder.

I was facing this error due to a bug in my code. I was trying to extract (conn.getInputStream()) from a different connection object than what it should have been. I fixed the connection object variable and it started working.
BufferedImage image;
try (InputStream in = new BufferedInputStream(conn.getInputStream())) {
image = ImageIO.read(in);
File file = new File(fullImageFilePath);
synchronized (file.getCanonicalPath().intern()) {
if (!file.exists()) {
ImageIO.write(image, "png", file);
}
}
}

Instead of
this.icon = ImageIO.read(this.getClass().getResourceAsStream("/resources/" + imgName));
Use
this.icon = ImageIO.read(new File("Full Path");
I do not know why the first snippet does not work, but new File() has always worked for me.

You can try this:
image = ImageIO.read(getClass().getResource("/resources/" + imgName));

Try This
private BufferedImage get(String path) throws IOException{
URL url = this.getClass().getClassLoader().getResource(path);
String thing = url.getFile();
return ImageIO.read(new File(thing));
}

Related

How to get .jar resources path?

I'm using a custom method to get pictures from the resources/ folder. The hardcoded path works well when programming during production (src/main/resources/). However when delivering, I would need to make this path relative to the .jar root. So I made this.
public static Image getImageFromFile(String file)
{
Image image = null;
try
{
String path = FileUtils.class.getClassLoader().getResource(file).toExternalForm();
System.out.println(path);
File pathToFile = new File(path);
image = ImageIO.read(pathToFile);
}
catch (IOException ex) {ex.printStackTrace();}
return image;
}
file:/C:/Users/Hugo/Desktop/Hugo/Java%20Workspace/ClashBot/bin/main/icons/level-label.png
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at com.lycoon.clashbot.utils.FileUtils.getImageFromFile(FileUtils.java:55)
The printed path is valid and points to the corresponding picture. However, the program raises an IOException.
Why can't it find the file?
You're jumping through way too many hoops. It's quite simple:
FileUtils.class.getResource("path.png");
// -OR-
try (var in = FileUtils.class.getResourceAsStream("path.png")) {
// in is an inputstream.
}
is all you need. Note that this means the path.png file is searched for in the exact same place (and even same 'subdir') as where FileUtils lives. So if you have, say, a file on C:\Projects\Hugo\MyApp\myapp.jar, and if you were to unzip that, inside you'd find com/foo/pkg/FileUtils.class, then the string path.png would look in that jar, and for com/foo/pkg/path.png. In other words, AnyClass.class.getResource("AnyClass.class") will let a class find its own class file. If you want to go from the 'root' of the jar, add a slash, i.e. FileUtils.class.getResource("/path.png") looks in the same jar, and for /path.png inside that jar.
getResource returns a URL. getResourceAsStream returns a stream (which you need to close; use try-with-resources as I did). Just about every resource-using API out there will take one of these two as input. For example, ImageIO does so; it even takes a URL so you can use either one:
var image = ImageIO.read(FileUtils.class.getResource("imgName + ".png"));
Yes. It's a one-liner. This will load images straight from within a jar file!
You could try to use a slightly different call like this:
java.net.URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(file);
String filePath = URLDecoder.decode(fileUrl.getPath(), "UTF-8");
image = ImageIO.read(filePath);

Unable to locate/open image inside exported jar

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();
}

Absolute Path of a Local File Object

so I'm looking towards porting a .jar to an executable and am cleaning my code up a bit before I do that. Right now I have the following:
BufferedImage bgImg = null;
//Grabs the background image
try {
bgImg = ImageIO.read(new File(""));
} catch (IOException e1) {
e1.printStackTrace();
}
I have several other images that I can just use:
new ImageIcon(getClass().getResource("imagename.png")));
However, since the former is a File object it does not take the same type of argument. I was wondering if there is something similar that I can use for that, or if there is some other way to make the File absolute so that there are no errors when porting to an executable. Thanks!
Use the read(InputStream input) method instead with Class.getResourceAsStream().
For example:
bgImg = ImageIO.read(getClass().getResourceAsStream("imagename.png"));
I'm not sure what you want to do. But you can access a file in your current working directory with a dot before the path.
E.g.
ImageIO.read(new File("./imagename.png"));

Java jar not reading files from the jar, only external folders?

When ever I make a JAR, the JAR won't read the folder inside it, only a folder in the folder the JAR is it. OK, that wasn't very descriptive. So here is a photo I edited to support.
I hope you get the idea now. So how would I fix this? I already have res and stats part of the build path in eclipse, now what?
Code I use to read the resources:
Image player;
player = new ImageIcon("res/player.png").getImage();
When using ImageIcon and passing it a String, it expects that the parameter refers to a File.
From the JavaDocs
Creates an ImageIcon from the specified file. ... The specified String
can be a file name or a file path
Files and "resources" are different things.
Instead, try using something more like...
new ImageIcon(getClass().getResource("res/player.png"));
Assuming that res/player.png resides within the jar in side the res directory.
Depending on the relationship to the class trying to load the resource and the resource's location, you may need to use
new ImageIcon(getClass().getResource("/res/player.png"));
instead...
Updated
Some recommendations, as EJP has pointed, you should be prepared for the possibility that the resource won't be found.
URL url = getClass().getResource("/res/player.png");
ImageIcon img = null;
if (url != null) {
img = new ImageIcon(url);
}
// Deal with null result...
And you should be using ImageIO.read to read images. Apart from the fact that it supports more (and can support more into the future) image formats, it loads the image before returning and throws an IOException if the image can't be read...
URL url = getClass().getResource("/res/player.png");
ImageIcon icon = null;
if (url != null) {
try {
BufferedImage img = ImageIO.read(url);
icon = new ImageIcon(img);
} catch (IOException exp) {
// handle the exception...
exp.printStackTrace();
}
}
// Deal with null result...

Changing the location of files in Java application

I've been putting all of my images for my Java application in a package called "rtype" inside src where I also also have my Class that deals with these images. I wanted to sort the images and put them in a folder of their own. When I do this, The images will no longer load into the class, and I know it's because I changed the file path. I've done some research and tried a few different things. This is basically what I had originally:
String walkingDown = "WalkingDown.gif";
ImageIcon ii;
Image image;
ii = new ImageIcon(this.getClass().getResource(walkingDown));
image = ii.getImage();
and It worked just fine before I moved the location of the images outside the location of the class. Now it cant find the images. Here is what I tried and found online to try (The folders Name is Sprites):
//use getClassLoader() inbetween to find out where exactly the file is
ii = new ImageIcon(this.getClass().getClassLoader().getResource(standingDown));
and
//Changing the path
String walkingDown = "src\\Sprites\\WalkingDown.gif";
//also tried a variation of other paths with no luck
I am using the C drive, but don't want to use "C" in my extension, as I want it to be accessible no matter where I put the project. I am fairly stuck at this point and have done enough looking into it to realize that It was time to ask.
I have a separate "package" for images with that name (in the src folder)
Try something like this:
try {
ClassLoader cl = this.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("images/WalkingDown.gif"));
}
catch(Exception imageOops) {
System.out.println("Could not load program icon.");
System.out.println(imageOops);
}
Your variable is named walkingDown, but you pass in standingDown to the getResource() method.
new ImageIcon("src/Sprites/WalkingDown.gif");

Categories

Resources