How do you load a java.awt.Image
object from a file, and know when it has loaded?
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(); }
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With