Java Graphics How to - Use the subImage(Rectangle) method to create the smaller image








Question

We would like to know how to use the subImage(Rectangle) method to create the smaller image.

Answer

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
//  w  ww . j  a  va  2  s.c om
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Main {

  public static void main(String[] args) throws Exception {
    Robot robot = new Robot();
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    BufferedImage image = robot.createScreenCapture(new Rectangle(d));
    BufferedImage sub = image.getSubimage(0, 0, 400, 400);
    File f = new File("SubImage.png");
    ImageIO.write(sub, "png", f);
    final ImageIcon im = new ImageIcon(f.toURI().toURL());

    Runnable r = new Runnable() {

      @Override
      public void run() {
        JOptionPane.showMessageDialog(null, new JLabel(im));
      }
    };
    SwingUtilities.invokeLater(r);
  }
}