Java標准API中有個Robot類,該類可以實現屏幕截圖,模擬鼠標鍵盤操作這些功能。這裡只展示其屏幕截圖。
截圖的關鍵方法createScreenCapture(Rectangle rect) ,該方法需要一個Rectangle對象,Rectangle就是定義屏幕的一塊矩形區域,構造Rectangle也相當容易:
new Rectangle(int x, int y, int width, int height),四個參數分別是矩形左上角x坐標,矩形左上角y坐標,矩形寬度,矩形高度。截圖方法返回BufferedImage對象,示例代碼:
/**
* 指定屏幕區域截圖,返回截圖的BufferedImage對象
* @param x
* @param y
* @param width
* @param height
* @return
*/
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;
}
如果需要把截圖保持為文件,使用ImageIO.write(RenderedImage im, String formatName, File output) ,示例代碼:
/**
* 指定屏幕區域截圖,保存到指定目錄
* @param x
* @param y
* @param width
* @param height
* @param savePath - 文件保存路徑
* @param fileName - 文件保存名稱
* @param 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();
}
}
捕捉屏幕截圖後,也許,我們需要對其剪裁。主要涉及兩個類CropImageFilter和FilteredImageSource,關於這兩個類的介紹,看java文檔把。
/**
* BufferedImage圖片剪裁
* @param srcBfImg - 被剪裁的BufferedImage
* @param x - 左上角剪裁點X坐標
* @param y - 左上角剪裁點Y坐標
* @param width - 剪裁出的圖片的寬度
* @param height - 剪裁出的圖片的高度
* @return 剪裁得到的BufferedImage
*/
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;
}
如果剪裁後需要保存剪裁得到的文件,使用ImageIO.write,參考上面把截圖保持為文件的代碼。