the best way to load image in java

What is the best way in java to load an image from file in application . Can you post some example code?
[111 byte] By [jproga] at [2007-11-26 15:13:16]
# 1

The best way depends on what you are doing. We have options.

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class ImageLoading {

public static void main(String[] args) {

ImageLoading test = new ImageLoading();

test.loadImages("images/cougar.jpg");

}

private void loadImages(String path) {

Image older = olderLoadImage(path);

Image newer = newerLoadImage(path);

BufferedImage newest = newestLoadImage(path);

JPanel panel = new JPanel(new GridLayout(1,0,2,0));

panel.add(wrap(older));

panel.add(wrap(newer));

panel.add(wrap(newest));

JOptionPane.showMessageDialog(null, panel, "",

JOptionPane.PLAIN_MESSAGE);

}

private JLabel wrap(Image image) {

return new JLabel(new ImageIcon(image));

}

private Image olderLoadImage(String path) {

Image image = Toolkit.getDefaultToolkit().createImage(path);

MediaTracker mt = new MediaTracker(new Component() {});

mt.addImage(image, 0);

try {

mt.waitForID(0);

} catch(InterruptedException e) {

System.out.println("mt interrupted");

}

if(mt.isErrorAny()) {

int status = mt.statusAll(false);

printError(status, path);

}

return image;

}

private Image newerLoadImage(String path) {

ImageIcon icon = new ImageIcon(path);

int status = icon.getImageLoadStatus();

if(status != MediaTracker.COMPLETE)

printError(status, path);

return icon.getImage();

}

private void printError(int status, String path) {

String s = "Image loading error for " + path + ": ";

switch(status) {

case MediaTracker.ABORTED:

s += "ABORTED";

break;

case MediaTracker.COMPLETE:

s += "COMPLETE";

break;

case MediaTracker.ERRORED:

s += "ERRORED";

break;

case MediaTracker.LOADING:

s += "LOADING";

break;

default:

System.out.println("unexpected status: " + status);

}

System.out.println(s);

}

private BufferedImage newestLoadImage(String path) {

BufferedImage image = null;

try {

image = ImageIO.read(new File(path));

} catch(Exception e) {

System.out.println(e.getClass().getName() + ": " +

e.getMessage());

}

return image;

}

}

crwooda at 2007-7-8 9:04:27 > top of Java-index,Security,Cryptography...