java 在java中从项目的文件夹加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17132196/
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
load an image from project's folder in java
提问by Aimad Majdou
I want to load an image which is in my projet folder as : /src/images/URL.jpg
我想加载我的 projet 文件夹中的图像: /src/images/URL.jpg
I tried this code :
我试过这个代码:
BufferedImage image = ImageIO.read(getClass().getResource("/images/URL.jpg"));
But I'm getting this error :
但我收到此错误:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Personel.PersonnelMainForm.print(PersonnelMainForm.java:464)
How can I solve this problem ?
我怎么解决这个问题 ?
回答by Andrew Cumming
From personal experience I use:
根据个人经验,我使用:
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/images/image.jpg"));
I get the resource as a stream and that seems to work fine for me.
我以流的形式获取资源,这对我来说似乎很好用。
回答by Humungus
You can try thisversion of read
, which takes File as an argument.
你可以试试这个版本的read
,它以 File 作为参数。
BufferedImage image = ImageIO.read(new File("path"));
where path
is the path to you file, absolute or relative as you need.
path
您的文件路径在哪里,根据需要是绝对路径还是相对路径。
Another option, if you really want to load it as a resource, would be editing your classpath, as per this question.
另一种选择,如果你真的想将它作为资源加载,将根据这个问题编辑你的类路径。
回答by albgorski
I suppose you have a java class in the package. You have to move up so many times as package levels. Example: Java class is defined as org.test.MyClass you have to go up twice (../../) to be in the main directory.
我想你在包中有一个 java 类。您必须多次提升包裹级别。示例:Java 类定义为 org.test.MyClass 你必须上两次 (../../) 才能在主目录中。