如何在java中正确加载BufferedImage?

时间:2009-03-02 04:29:34

标签: java image loading bufferedimage

好的,所以我一直在尝试使用以下代码加载BufferedImage:

URL url = this.getClass().getResource("test.png");
BufferedImage img = (BufferedImage) Toolkit.getDefaultToolkit().getImage(url);

当我运行它时,这给了我一个类型转换错误,那么如何正确加载BufferedImage?

2 个答案:

答案 0 :(得分:90)

改为使用ImageIO.read()

BufferedImage img = ImageIO.read(url);

答案 1 :(得分:4)

BufferedImage img = null;
try {
    img = ImageIO.read(new File("D:\\work\\files\\logo.jpg"));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}