简体   繁体   English

无法加载图片

[英]Having trouble loading image

I've been trying to load this image.png file that's located in my images folder: 我一直在尝试加载这个位于我的images文件夹中的image.png文件:

In eclipse I've made a folder in my src folder called images and put the image there, so it should be part of my classpath. 在eclipse中,我在我的src文件夹中创建了一个名为images的文件夹并将图像放在那里,因此它应该是我的类路径的一部分。

However, when I try to use this image it does not work: 但是,当我尝试使用此图像时,它不起作用:

I've tried these: 我试过这些:

Image image; 
String craft = "myApp/src/images/image.png";
ImageIcon ii = new ImageIcon(craft); 
        image = ii.getImage();

Image image; 
String craft = "myApp/src/images/image.png"; 
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
        image = ii.getImage();

And various variations for String craft: String工艺的各种变化:

"images/image.png", "/images/image.png", "/myApp/src/images/image.png"

If you have the image in: 如果你有图像:

src/images/foo.png

And use this code: 并使用此代码:

ImageIcon ii = new ImageIcon("images/foo.png");
Image image = ii.getImage();
System.out.println(image != null);

The output will be: 输出将是:

true

... that is, the Image is not null ... ... if your classpath is the default build path eclipse provides when creating your project (note: should be the same with Netbeans, etc.). ...也就是说, Image不是null ......如果你的classpath是eclipse在创建你的项目时提供的默认构建路径(注意:应该与Netbeans相同,等等)。

If you're using a different building script, be it Ant or Maven, you might need to change the path. 如果您使用的是不同的构建脚本,无论是Ant还是Maven,您可能需要更改路径。 You will certainly if it's a web application. 如果它是一个Web应用程序,你肯定会。

Additional notes 补充笔记

  • Here is a good SO thread on resource paths for web applications. 是Web应用程序资源路径上的一个很好的SO线程。
  • Here is the typical Maven folder layout - useful to get you started if you use Maven as your build/package script. 是典型的Maven文件夹布局 - 如果您使用Maven作为构建/包脚本,可以帮助您入门。

Whenever you are trying to load a resource in classpath, you need to specify the correct relative path. 每当您尝试在类路径中加载资源时,都需要指定正确的相对路径。 if you have your images folder in classpath as that of the classes, then you have to load it as follows 如果您将类路径中的images文件夹作为类的文件夹,则必须按如下方式加载它

String craft = "images/image.png"; 
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));

or if you have all the files in images folder in classpath, you can just specify the file name directly as well 或者如果你在classpath中的images文件夹中有所有文件,你也可以直接指定文件名

   String craft = "image.png"; 
    ImageIcon ii = new ImageIcon(craft);

So, i am sure the path you have given is wrong and that's why the resource is not getting loaded 所以,我确信你给出的路径是错误的,这就是资源没有被加载的原因

Try this out 试试吧

String craft = "images/image.png"; 
ImageIcon ii = new ImageIcon(craft);

File structure 文件结构

ProjectRoot
          images
               imgage.png
          src
          bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM