如何在java中正确加载缓冲图像?

2022-09-01 02:15:37

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

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

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


答案 1

请改用 ImageIO.read() 代替:

BufferedImage img = ImageIO.read(url);

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

推荐