Java screen capture and clipping

  • 2020-04-01 03:29:02
  • OfStack

There is a Robot class in the Java standard API that takes screenshots and simulates these functions with a mouse and keyboard. Only screenshots are shown here.

The key method for the screenshot is createScreenCapture(Rectangle rect), which requires a Rectangle object, a Rectangle is a rectangular area of the screen that is defined, and it is fairly easy to construct a Rectangle:

New Rectangle(int x, int y, int width, int height), the four parameters are the upper left Rectangle x coordinate, the upper left Rectangle y coordinate, the Rectangle width, and the Rectangle height. Screenshot method returns BufferedImage object, sample code:


   
   public BufferedImage getScreenShot(int x, int y, int width, int height) {
    BufferedImage bfImage = null;
    try {
      Robot robot = new Robot();
      bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
    } catch (AWTException e) {
      e.printStackTrace();
    }
    return bfImage;
  }

  If you need to keep the screenshot as a File, use imageio.write (RenderedImage im, String formatName, File output), sample code:


   
  public void screenShotAsFile(int x, int y, int width, int height, String savePath, String fileName, String format) {
    try {
      Robot robot = new Robot();
      BufferedImage bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
      File path = new File(savePath);
      File file = new File(path, fileName+ "." + format);
      ImageIO.write(bfImage, format, file);
    } catch (AWTException e) {
      e.printStackTrace();  
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  After capturing the screenshot, maybe we need to crop it. Mainly involves two classes CropImageFilter and FilteredImageSource, about the introduction of these two classes, see the Java documentation.


   
  public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {
    BufferedImage cutedImage = null;
    CropImageFilter cropFilter = new CropImageFilter(x, y, width, height); 
    Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter)); 
    cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
    Graphics g = cutedImage.getGraphics(); 
    g.drawImage(img, 0, 0, null); 
    g.dispose(); 
    return cutedImage;
  }

If you need to save the clipped file after clipping, use imageio.write and refer to the code above to keep the screenshot as a file.


Related articles: