2014-03-19 148 views
0

我一直在试图弄清楚这几天。我正在尝试从我的res目录加载缓冲图像。我的文件夹层次是。加载缓存的图像

  • MainProjectFolder
    • RES
      • 我的图像被加载
    • SRC
      • 逻辑文件夹
        • loop.java(我的类来传递一个字符串到BufferedImageLoader被加载)
      • 图形文件夹
        • BufferedImageLoader.java(转换字符串的BufferedImage)

不过,我不断收到一个输入= NULL错误。我如何指向我的图像文件?

我的环型

BufferedImageLoader loader = new BufferedImageLoader(); 
    try{ 
     spriteSheet = loader.loadImage("/res/sprite_sheet_test.png"); 

    }catch(IOException e){ 
     e.printStackTrace(); 
    } 

我BufferedImageLoaderClass

public BufferedImage loadImage(String path)throws IOException{ 
    url = this.getClass().getResource(path); 
    image = ImageIO.read(url); 
    newImage = new BufferedImage(image.getWidth(), image.getHeight(), 
      BufferedImage.TYPE_INT_ARGB); 
    Graphics2D g = newImage.createGraphics(); 
    g.drawImage(image, 0, 0, null); 
    g.dispose(); 
    return newImage; 
} 

感谢您的帮助!

+0

请用堆栈跟踪更新问题!另外,您确定要将图像作为文件加载吗?在类路径中放置res /'通常更容易,并且作为资源加载('getClass()。getResource(path_without_res_prefix)')。谷歌或搜索类似的问题。 – haraldK

+0

我是一种新的Java,仍然在学习绳索。我可以像你说的那样加载图像。通过使用url = this.getClass()。getResource(path)但是,我会在字符串路径中指向包含我的图像的文件夹的内容? – seiko149

回答

0

鉴于该文件夹res被定义为项目中的资源文件夹,并把类路径上(实际上,包含文件sprite_sheet_test.png),这应该工作:

loader.loadImage("/sprite_sheet_test.png"); 

注意龙头/,以确保图像是从资源根加载的。没有它,该资源将被解析为相对于您的BufferedImageLoader类的包。

+0

如果我声明绝对路径 – seiko149

+0

@ seiko149,那么dosent工作或者唯一有效的工作如果它不起作用,那是因为'res'不是您班级路径的一部分。 – haraldK

+0

我通过将资源文件夹添加到类路径中来使其在Eclipse中工作。但是,当我尝试在命令行中编译它或导出到可运行的jar时,映像不能加载。我想我需要做更多的关于如何声明路径的研究。感谢您的帮助让它运行。 – seiko149