且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用eclipse将图像添加到java项目中?

更新时间:2023-02-16 23:32:13

将图像放在源文件夹,而不是常规文件夹。也就是:右键单击项目 - >新建 - >源文件夹。将图像放在该源文件夹中。然后:

  InputStream input = classLoader.getResourceAsStream(image.jpg); 

请注意,路径被省略。这是因为图像直接位于路径的根部。您可以在源文件夹下添加文件夹,如果您喜欢则将其进一步分解。或者您可以将图像放在现有的源文件夹下(通常称为 src )。


I've done a lot of reading around SO and Google links.

I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.

Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)

Here is my method.

I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"

Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".

Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.

I then use the following code:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);

And at this point, I run the test program and get this error:

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at Test.main(Test.java:17)

Thanks for any help in advance!

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).