Java Tutorial/2D Graphics/ImageReader
Show Image with ImageReader
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JFrame;
public class Main extends Panel{
private BufferedImage images[];
private int imageIndex = 0;
public Main(String filename) throws Exception{
FileInputStream fin = new FileInputStream(filename);
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
System.out.println("suf " + suffix);
Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
ImageReader imageReader = (ImageReader) readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(fin);
imageReader.setInput(iis, false);
int num = imageReader.getNumImages(true);
images = new BufferedImage[num];
for (int i = 0; i < num; ++i) {
images[i] = imageReader.read(i);
}
fin.close();
}
public void paint(Graphics g) {
if (images == null)
return;
g.drawImage(images[imageIndex], 0, 0, null);
imageIndex = (imageIndex + 1) % images.length;
}
static public void main(String args[]) throws Exception {
JFrame frame = new JFrame("ShowImageIR.java");
Panel panel = new Main(args[0]);
frame.getContentPane().add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}