Java Graphics How to - Read part of BufferedImage








Question

We would like to know how to read part of BufferedImage.

Answer

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/*from  ww w.jav  a 2 s.  c  o  m*/
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    Image chunk = readFragment(url.openStream(), new Rectangle(15, 15, 30,
        25));
    JOptionPane.showMessageDialog(null, new ImageIcon(chunk), "Duke",
        JOptionPane.INFORMATION_MESSAGE);

  }
  public static BufferedImage readFragment(InputStream stream, Rectangle rect)
      throws IOException {
    ImageInputStream imageStream = ImageIO.createImageInputStream(stream);
    ImageReader reader = ImageIO.getImageReaders(imageStream).next();
    ImageReadParam param = reader.getDefaultReadParam();

    param.setSourceRegion(rect);
    reader.setInput(imageStream, true, true);
    BufferedImage image = reader.read(0, param);

    reader.dispose();
    imageStream.close();

    return image;
  }

}