user2277362
user2277362

Reputation: 113

ImageIO is not loading an image

I am have trouble loading an image with java code. I have the image, i.png in the same package as the class this code is in. This is the code.

    Image img;
    try
    {
        img = ImageIO.read(new File("i.png"));
    }
    catch(IOException e)
    {
    }

When i execute this code it throws an IOException and says it cannot read the input file.
Would anybody know why it might throw that exception Sorry for the bad wording what i ment is the code throws an exception then you obviosly can'nt use it later in the code(Thats what i get for staying up till 11:30)
Thanks for the help!

Upvotes: 2

Views: 395

Answers (2)

user1046143
user1046143

Reputation: 66

Its a bad practice to hard code paths in your code or keep the resources in the same package just to make the access easy. You can give either the hard coded path or use the getResourceAsStream

getResourceAsStream's documentation says

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

This is what you want with your code.

Read this answer to get a bit more clarity on file way of accessing resources vs classloader way of accessing resources.

So, with some modification your code works when it is changed like this -

public class TestIt {
public static void main(String[] args) throws IOException {

Image img = null;
img = ImageIO.read(TestIt.class.getResourceAsStream( "i.png" ));
img.getGraphics();
System.out.println(img);
}

}

Notice the use of getResourceAsStream method.

HTH

Upvotes: 2

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

You are getting null pointer exception because your img variable stays null after executing img = ImageIO.read(new File("i.png")). Because it stays null, you are getting null pointer exception while trying to use it further in the code.

Here is your solution:

BufferedImage img = ImageIO.read(new File("i.png"));

Regards, Ravi

Upvotes: 0

Related Questions