Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly load a BufferedImage in java?

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?

like image 630
William Avatar asked Mar 02 '09 04:03

William


People also ask

What is BufferedImage in Java?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).

What is BufferedImage in Java 2D?

The BufferedImage class is a cornerstone of the Java 2D immediate-mode imaging API. It manages the image in memory and provides methods for storing, interpreting, and obtaining pixel data.


2 Answers

Use ImageIO.read() instead:

BufferedImage img = ImageIO.read(url); 
like image 100
Zach Scrivena Avatar answered Sep 28 '22 02:09

Zach Scrivena


BufferedImage img = null; try {     img = ImageIO.read(new File("D:\\work\\files\\logo.jpg")); } catch (IOException e) {     // TODO Auto-generated catch block     e.printStackTrace(); } 
like image 43
Usman Avatar answered Sep 28 '22 04:09

Usman