Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

How to set the right path to image in java?

I am trying to load and draw it with paint method in java whatever the way I write the path it always shows an exception

java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)

I have the image at the same folder with the class

This is the line that I am loading image in

    Image img = ImageIO.read(getClass().getResourceAsStream("pepsi.png"));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have a look at MKYong's tutorial. It shows you where to put your image. If you want the image to be loaded as "resource", you have to put it in the resources folder. You project structure would be like this:

MyProject
    +--src
        +--main
            +--java
            |    +-com
            |       +--me
            |           +--Main.java
            +--resources
                 +--pepsi.jpg

and in your Main class you execute that snippet:

try {
    Image img= ImageIO.read(Main.class.getClassLoader().getResourceAsStream("pepsi.jpg"));
    System.out.println(img.getWidth(null));  //this is just a test, when it prints out the width of your image, you have the right file loaded 
} catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...