Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.awt.Image from File

How do you load a java.awt.Image object from a file, and know when it has loaded?

like image 468
milo Avatar asked Aug 29 '11 04:08

milo


3 Answers

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(); } 
like image 69
Dragon8 Avatar answered Oct 05 '22 03:10

Dragon8


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(); 
like image 44
Nicolas Modrzyk Avatar answered Oct 05 '22 03:10

Nicolas Modrzyk


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();
like image 23
Atom 12 Avatar answered Oct 05 '22 01:10

Atom 12