How do I properly load a BufferedImage in java?

William picture William · Mar 2, 2009 · Viewed 62.3k times · Source

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?

Answer

Zach Scrivena picture Zach Scrivena · Mar 2, 2009

Use ImageIO.read() instead:

BufferedImage img = ImageIO.read(url);