简体   繁体   English

使用ClassLoader.getResource()加载BufferedImage

[英]loading BufferedImage with ClassLoader.getResource()

I am trying to load an image file (gif) which is stored locally in the same directory as my Eclipse java project: 我正在尝试加载一个图像文件(gif),该图像文件本地存储在与Eclipse Java项目相同的目录中:

ref is the relative path where the gif image is stored. 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);
       }
}

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. 在Eclipse工作区中,在我的项目目录中,我有一个文件夹sprites ,其中存储了gif图像。 But the client code always returns: Can't find ref: sprites/ship.gif 但是客户端代码总是返回: Can't find ref: sprites/ship.gif

Am I doing something wrong in my approach above to load the gif image? 我在上面的方法中加载gif图片时做错了吗? Is there a better more straightforward way to do a file lookup in this case? 在这种情况下,是否有更好的直接方法来执行文件查找?

Many thanks for any advice. 非常感谢您的任何建议。

The getResource() method searches your classpath to find the file, likely the sprites directory is not in your classpath. getResource()方法搜索您的类路径以找到文件,很可能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 . 尝试打开项目属性-> Java Build Path ,选择Libraries选项卡,然后单击Add Class Folder按钮,然后选择sprites的父目录。

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

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