There is a robot class in the Java Standard API that enables screen captures to simulate mouse-keyboard operations. This shows only its screenshot.
The key method of screenshot createscreencapture (Rectangle rect), which requires a Rectangle object, Rectangle is to define a rectangular area of the screen, the construction of Rectangle is also quite easy:
New Rectangle (int x, int y, int width, int height), four parameters are rectangle upper left corner x coordinate, rectangle upper left corner y coordinate, rectangle width, rectangle height. Screenshot method returns the BufferedImage object, sample code:
/**
* Specify screen area screenshot, return screenshot BufferedImage Object
* @param x
* @param y
* @param width
* @param height
* return
*
/public bufferedimage getscreenshot (int x, int y, int width, int height) {
bufferedimage bfimage = nu ll;
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:
/**
* Specify screen area screenshot, save to specified directory
* @param x
* @param y
* @param width
* @param height
* @param savepath-File Save Path
* @param filename-File Save name
* @param format-file format
*
/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 trim it. Mainly involves two classes CropImageFilter and FilteredImageSource, the introduction of these two classes, look at the Java document.
/**
* bufferedimage picture Tailoring
* @param srcbfimg-trimmed bufferedimage
* @param x-upper left corner trim point x coordinate
* @param y-upper left corner trim Point y sit Mark
* @param width-The breadth of the cropped picture
* @param height-cropped picture Heights
* @return Trimmed bufferedimage * * Public
Buffe Redimage cutbufferedimage (bufferedimage srcbfimg, int x, int y, int width, int height) {
BufferedImage cutedimage = n ull;
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 cropped file after clipping, use Imageio.write to refer to the code that holds the screenshot as a file.