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.
Just use the read method of the Java ImageIO class, and you can open/read images in a variety of formats (GIF, JPG, PNG) in basically one line of Java code.
The IllegalArgumentException is an unchecked exception in Java that is thrown to indicate an illegal or unsuitable argument passed to a method. It is one of the most common exceptions that occur in Java.
ImageIO. A class containing static convenience methods for locating ImageReader s and ImageWriter s, and performing simple encoding and decoding. ImageReader. An abstract superclass for parsing and decoding of images.
Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With