8

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

eltabo
  • 3,749
  • 1
  • 21
  • 33
Kumara
  • 117
  • 2
  • 10

2 Answers2

8

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) );
sfletche
  • 47,248
  • 30
  • 103
  • 119
  • I tried `.createScreenCapture(300, 300, 200, 200)`, but it returns an error: cannot be applied to given types... – Kumara May 14 '14 at 16:34
  • sorry. just checked the [docs](http://docs.oracle.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)) to see that `createScreenCapture` takes a `Rectangle` object. edited my answer. should work now. – sfletche May 14 '14 at 16:50
0
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);
        }
    }

}