java 从项目文件夹内的文件加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29780369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:55:59  来源:igfitidea点击:

Load image from a file inside a project folder

javajavafx

提问by Astinog

I'm trying to load an image from a file without using a FileChooser. The folders are:

我正在尝试从文件加载图像而不使用FileChooser. 这些文件夹是:

TestProject
-src
--application
---(all_the_classes_i'm_using.java)
-assets
--drawIcon.png

I want to load the image in the assets folder. I've tried:

我想在资产文件夹中加载图像。我试过了:

Image image = new Image("../assets/drawIcon.png")
Image image = new Image(getClass().getResourceAsStream("../assets/drawIcon.png"))

I've tried it with the string path "/TestProject/assets/drawIcon.png", but nothing. I don't understand how to load this image!

我已经用字符串路径“/TestProject/assets/drawIcon.png”试过了,但没有。我不明白如何加载此图像!

回答by botismarius

Set the assetsdirectory as a resource directory and then load the image as a resource from the location "/drawIcon.png":

assets目录设置为资源目录,然后从位置“/drawIcon.png”加载图像作为资源:

URL url = getClass().getResource("/drawIcon.png");
Image image = ImageIO.read(url);

In case you want to create a javafx Image:

如果你想创建一个 javafx 图像:

Image image = new Image("/drawIcon.png");

In this case, also, mark that folder as resource folder.

在这种情况下,还要将该文件夹标记为资源文件夹。

More info here: https://docs.oracle.com/javafx/2/api/javafx/scene/image/Image.html

更多信息:https: //docs.oracle.com/javafx/2/api/javafx/scene/image/Image.html

回答by Florin Virtej

You can use getResource(path).toString(); the path must start with /, and it starts with the verry first package in your src folder.

您可以使用 getResource(path).toString(); 路径必须以 / 开头,并且以 src 文件夹中的第一个包开头。

Image img= new Image(getClass().getResource("/path/in/your/package/structure/icon.png").toString());

Image img= new Image(getClass().getResource("/path/in/your/package/structure/icon.png").toString());