使用 ClassLoader.getResource() 加载 BufferedImage
我正在尝试加载一个图像文件 (gif),该文件本地存储在与我的 Eclipse java 项目相同的目录中:
ref
是存储 gif 图像的相对路径。
public Sprite getSprite(String ref) {
BufferedImage sourceImage = null;
try {
URL url = this.getClass().getClassLoader().getResource(ref);
if (url == null) {
fail("Can't find ref: "+ref);
}
sourceImage = ImageIO.read(url);
} catch (IOException e) {
fail("Failed to load: "+ref);
}
}
使用上述方法的客户端代码是:
public Entity(String ref,int x,int y) {
this.sprite = ResourceManager.getSprite("sprites/alien.gif");
this.x = x;
this.y = y;
}
在 Eclipse 工作区和我的项目目录中,我有一个文件夹 sprites
,其中存储有 gif 图像。但客户端代码总是返回: Can't find ref: sprites/ship.gif
我在上面加载 gif 图像的方法中做错了什么吗?在这种情况下,是否有更好更直接的方法来进行文件查找?
非常感谢您的任何建议。
I am trying to load an image file (gif) which is stored locally in the same directory as my Eclipse java project:
ref
is the relative path where the gif image is stored.
public Sprite getSprite(String ref) {
BufferedImage sourceImage = null;
try {
URL url = this.getClass().getClassLoader().getResource(ref);
if (url == null) {
fail("Can't find ref: "+ref);
}
sourceImage = ImageIO.read(url);
} catch (IOException e) {
fail("Failed to load: "+ref);
}
}
The client code that uses the above method is:
public Entity(String ref,int x,int y) {
this.sprite = ResourceManager.getSprite("sprites/alien.gif");
this.x = x;
this.y = y;
}
In the Eclipse workspace and within my project directory I have a folder sprites
with the gif images stored there. But the client code always returns: Can't find ref: sprites/ship.gif
Am I doing something wrong in my approach above to load the gif image? Is there a better more straightforward way to do a file lookup in this case?
Many thanks for any advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getResource()
方法搜索您的类路径以查找该文件,sprites 目录可能不在您的类路径中。尝试打开您的项目属性 ->
Java Build Path
,选择Libraries
选项卡并单击Add Class Folder
按钮,然后选择sprites的父目录。The
getResource()
method searches your classpath to find the file, likely the sprites directory is not in your classpath.Try open your project properties ->
Java Build Path
, selectLibraries
tab and click onAdd Class Folder
button then select the parent directory of sprites.