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 wid, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth, int heightth ) { 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); (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, widter = hex,mg iter(x, y, widage ix, y, ImageFilter(x, y, pFilter = hex,mg iter(x, y, widage igage, xidage igage(x, y, Image, x, ) d; Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter)); cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_R); g.drawImage(img, 0, 0, null); g.dispose(); return cutedImage; }
如果剪裁後需要儲存剪裁得到的文件,使用ImageIO.write,參考上面把截圖保持為文件的程式碼。