41

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

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

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

4

2 回答 2

103

改用ImageIO.read()

BufferedImage img = ImageIO.read(url);
于 2009-03-02T04:35:08.220 回答
5
BufferedImage img = null;
try {
    img = ImageIO.read(new File("D:\\work\\files\\logo.jpg"));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
于 2015-09-02T04:41:08.040 回答