Question

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)?

Was it helpful?

Solution

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) );

OTHER TIPS

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);
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top