43

Okay, so I've been trying to load a BufferedImage using this code:

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

This gives me a type cast error when I run it though, so how do I properly load a BufferedImage?

Zach Scrivena
  • 29,073
  • 11
  • 63
  • 73
William
  • 8,630
  • 23
  • 77
  • 110
  • Even if you have reasons to use Toolkit over ImageIO, this isn't the best method to call, because it will hold on to the image even after you're done with it. A better method to call is Toolkit.createImage(URL url) – MiguelMunoz Sep 08 '21 at 07:16
  • Cast fails with Oracle-Java 8: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage – Sam Ginrich Dec 04 '22 at 10:18

2 Answers2

107

Use ImageIO.read() instead:

BufferedImage img = ImageIO.read(url);
Zach Scrivena
  • 29,073
  • 11
  • 63
  • 73
  • 1
    If you're looking for a pure Java alternative to `ImageIO` (ex: security reasons), there is [Apache Commons Imaging](https://commons.apache.org/proper/commons-imaging/) – ATOMP Aug 13 '21 at 18:19
6
BufferedImage img = null;
try {
    img = ImageIO.read(new File("D:\\work\\files\\logo.jpg"));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Usman
  • 1,116
  • 11
  • 13