How to capture only a desired portion of screen using createScreenCapture

强颜欢笑 提交于 2021-02-08 14:11:58

问题


The following code captures the screen:

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;


public class capture{
    public static void main(String args[]) { 

        try { 
            Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); 
            Robot robot = new Robot(); 
            BufferedImage img = robot.createScreenCapture(new Rectangle(size)); 
        } catch(Exception e) { 
        } 

    }
}

Is there a way, to capture only a desired portion of the screen (e.g. a rectangle, from one x,y point to another)?


回答1:


You can set the x and y of the top left corner, along with the width, and height dimensions of the rectangle to capture like this:

BufferedImage img = robot.createScreenCapture( new Rectangle(x, y, width, height) );



回答2:


import java.awt.AWTException;
import java.awt.Component;
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;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * This program demonstrates how to capture screenshot of a portion of screen.
 * 
 *
 */
public class TaskBarCaptureImage {

    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            String format = "jpg";
            String fileName = "TaskBar Captured." + format;

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            System.out.println("ScreenSize : " + screenSize);
            Rectangle captureRect = new Rectangle(0, 728, 1366, 40); // taskbar
                                                                        // zone

            BufferedImage screenFullImage = robot.createScreenCapture(captureRect);
            ImageIO.write(screenFullImage, format, new File(fileName));
            int no = 1;
            ImageIO.write(screenFullImage, format, new File("./imagenes/" + no + ".png"));


            System.out.println("TaskBar Captured!");
        } catch (AWTException | IOException ex) {
            System.err.println(ex);
        }
    }

}


来源:https://stackoverflow.com/questions/23660150/how-to-capture-only-a-desired-portion-of-screen-using-createscreencapture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!