开发者

java.awt.Image from File

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜