Show Image with ImageReader : ImageReader « 2D Graphics GUI « Java

Show Image with ImageReader


import java.awt.Graphics;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.swing.JFrame;

public class Main extends Panel {
  private BufferedImage images[];

  private int imageIndex = 0;

  public Main() throws Exception {
    String filename = "a.png";
    FileInputStream inputStream = new FileInputStream(filename);
    String extensionName = filename.substring(filename.lastIndexOf('.') + 1);
    Iterator readers = ImageIO.getImageReadersBySuffix(extensionName);
    ImageReader imageReader = (ImageReader);
    ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
    imageReader.setInput(imageInputStream, false);
    int num = imageReader.getNumImages(true);
    images = new BufferedImage[num];
    for (int i = 0; i < num; ++i) {
      images[i] =;

  public void paint(Graphics g) {
    if (images == null)
    g.drawImage(images[imageIndex], 0, 0, null);
    imageIndex = (imageIndex + 1) % images.length;

  static public void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    Panel panel = new Main();
    frame.setSize(400, 400);


Related examples in the same category

1.Add Image IO Read Progress Listener to ImageReader
2.Read an Image from a file
3.Read an Image from inputStream
4.Read an Image from URL
5.Determining the Format of an Image in a File
6.Detect the file type of the input stream prior to reading the image
7.List the image formats that can be read and written
8.Get file format, image resolution, number of bits per pixel (JPEG, GIF, BMP, PCX, PNG, IFF, RAS, PBM, PGM, PPM, PSD and SWF files)
9.Image format info
10.Image observer blocks until the image is completely loaded. AWT defers the loading of images until they are painted on a graphic.