如何在Java中为图像设置正确的路径? [英] How to set the right path to image in java?

查看:91
本文介绍了如何在Java中为图像设置正确的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论我写路径总是显示异常的方式,我都尝试用java中的paint方法加载和绘制它

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"));

推荐答案

看看

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

,然后在您的 Main 类中执行该代码段:

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

这篇关于如何在Java中为图像设置正确的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆