使用ClassLoader.getResource()加载BufferedImage [英] loading BufferedImage with ClassLoader.getResource()

查看:216
本文介绍了使用ClassLoader.getResource()加载BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载一个图像文件(gif),该文件本地存储在与我的Eclipse java项目相同的目录中:

I am trying to load an image file (gif) which is stored locally in the same directory as my Eclipse java project:

ref 是存储gif图像的相对路径。

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;
    }

在Eclipse工作区和项目目录中,我有一个文件夹 sprites ,其中存储了gif图像。但是客户端代码总是返回:找不到ref:sprites / ship.gif

In the Eclipse workspace and within my project directory I have a folder spriteswith the gif images stored there. But the client code always returns: Can't find ref: sprites/ship.gif

我在做什么我上面的方法错误加载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?

非常感谢任何建议。

推荐答案

getResource()方法搜索类路径以查找文件,可能是精灵目录不在您的类路径中。

The getResource() method searches your classpath to find the file, likely the sprites directory is not in your classpath.

尝试打开项目属性 - > Java构建路径 ,选择选项卡,然后单击添加类文件夹按钮,然后选择 sprites 。

Try open your project properties -> Java Build Path, select Libraries tab and click on Add Class Folder button then select the parent directory of sprites.

这篇关于使用ClassLoader.getResource()加载BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆