简体   繁体   English

从资源文件夹加载图像

[英]Loading an image from the Resource Folder

The code I am using to load the image is: 我用来加载图像的代码是:

 ImageIO.read(SpriteSheet.class.getResource(path));

The path being the path to the resource. 路径是资源的路径。 But it would error with IllegalArgumentException . 但是使用IllegalArgumentException会出错。 I wondered what might be causing and came to the conclusion that the resource should be added into the same path as the class. 我想知道可能是什么原因,并得出结论,应该将资源添加到与类相同的路径中。

Is it possible to load the image from another folder, like a res folder outside of the bin folder? 是否可以从其他文件夹(例如bin文件夹外部的res文件夹)加载图像? (folder holding compiled classes) (文件夹包含已编译的类)

EDIT: So i messed around with a few things, and came to a solution. 编辑:所以我弄乱了一些事情,并提出了解决方案。 But now I have another problem. 但是现在我有另一个问题。 Here is my code 这是我的代码

    File sheet = new File(SpriteSheet.class.getProtectionDomain().getCodeSource().getLocation().getPath());
URI uri = sheet.toURI();
    BufferedImage image = ImageIO.read(uri.toURL());

When I try to run it, it gives me an IIOException: Can't read Input File This means that I can never actually get it work. 当我尝试运行它时,它给了我IIOException: Can't read Input File这意味着我永远无法真正使它工作。 I tried debugging by prining the URL to the console and this is the URL. 我尝试通过将URL限定在控制台中来进行调试,这就是URL。 C:\\Users\\Amma\\Abhijeet\\Eclipse%20Workspace1\\Test%20Game\\bin The %20 comes in the middle. C:\\Users\\Amma\\Abhijeet\\Eclipse%20Workspace1\\Test%20Game\\bin %20位于中间。 Meaning that the file is and never can be acceesed. 这意味着该文件将永远无法访问。 Is there anyway I can fix this? 无论如何,我可以解决这个问题吗?

Thanks. 谢谢。

Class.getResource will return null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource. 如果找不到资源或调用者没有足够的特权来获取资源,则Class.getResource将返回null。 All variants of ImageIO.read will throw an IllegalArgumentException if they receive a null input. 如果ImageIO.read所有变体收到空输入,则将抛出IllegalArgumentException

Take a look at the documentation of the getResource to understand how an absolute resource name is constructed from the given resource named and what are the rules for searching resources. 查看getResource的文档,以了解如何从给定的资源名称构造绝对资源名称,以及搜索资源的规则是什么。

You can read images from any location as long as you have permissions to do so, the ImageIO.read method accepts a File, URL or InputStream so you have many option to do it. 只要您有权限,就可以从任何位置读取图像,ImageIO.read方法接受File,URL或InputStream,因此您有很多选择可以这样做。

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

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