Reputation: 555
How do you load a java.awt.Image
object from a file, and know when it has loaded?
Upvotes: 29
Views: 80109
Reputation: 14197
Use a java.awt.MediaTracker.
Here's a full example.
Basically,
toolkit = Toolkit.getDefaultToolkit();
tracker = new MediaTracker(this);
Image image = toolkit.getImage("mandel.gif");
tracker.addImage(image, 0);
tracker.waitForAll();
Upvotes: 7
Reputation:
I would use an ImageIcon
.
So doing, you don't have to bother about any checked exceptions. Also note that it uses a MediaTracker
when loading images from file resources.
ImageIcon icon = new ImageIcon("image.png");
Image image = icon.getImage();
Upvotes: 5
Reputation: 1805
The ImageIO
helper class offers methods to read and write images from/to files and streams.
To read an image from a file, you can use ImageIO.read(File)
(which returns a BufferedImage
).
But since BufferedImage
is a subclass of Image
, you can do:
try {
File pathToFile = new File("image.png");
Image image = ImageIO.read(pathToFile);
} catch (IOException ex) {
ex.printStackTrace();
}
Upvotes: 59