Java屏幕截圖及剪裁


  Java標准API中有個Robot類,該類可以實現屏幕截圖,模擬鼠標鍵盤操作這些功能。這里只展示其屏幕截圖。

  截圖的關鍵方法createScreenCapture(Rectangle rect) ,該方法需要一個Rectangle對象,Rectangle就是定義屏幕的一塊矩形區域,構造Rectangle也相當容易:

new Rectangle(int x, int y, int width, int height),四個參數分別是矩形左上角x坐標,矩形左上角y坐標,矩形寬度,矩形高度。截圖方法返回BufferedImage對象,示例代碼:

 

 1     /**
 2      * 指定屏幕區域截圖,返回截圖的BufferedImage對象
 3      * @param x
 4      * @param y
 5      * @param width
 6      * @param height
 7      * @return 
 8      */
 9     public BufferedImage getScreenShot(int x, int y, int width, int height) {
10         BufferedImage bfImage = null;
11         try {
12             Robot robot = new Robot();
13             bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
14         } catch (AWTException e) {
15             e.printStackTrace();
16         }
17         return bfImage;
18     }

 

 如果需要把截圖保持為文件,使用ImageIO.write(RenderedImage im, String formatName, File output) ,示例代碼:

 1     /**
 2      * 指定屏幕區域截圖,保存到指定目錄
 3      * @param x
 4      * @param y
 5      * @param width
 6      * @param height
 7      * @param savePath - 文件保存路徑
 8      * @param fileName - 文件保存名稱
 9      * @param format - 文件格式
10      */
11     public void screenShotAsFile(int x, int y, int width, int height, String savePath, String fileName, String format) {
12         try {
13             Robot robot = new Robot();
14             BufferedImage bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
15             File path = new File(savePath);
16             File file = new File(path, fileName+ "." + format);
17             ImageIO.write(bfImage, format, file);
18         } catch (AWTException e) {
19             e.printStackTrace();    
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23     }

 捕捉屏幕截圖后,也許,我們需要對其剪裁。主要涉及兩個類CropImageFilter和FilteredImageSource,關於這兩個類的介紹,看java文檔把。

 1     /**
 2      * BufferedImage圖片剪裁
 3      * @param srcBfImg - 被剪裁的BufferedImage
 4      * @param x - 左上角剪裁點X坐標
 5      * @param y - 左上角剪裁點Y坐標
 6      * @param width - 剪裁出的圖片的寬度
 7      * @param height - 剪裁出的圖片的高度
 8      * @return 剪裁得到的BufferedImage
 9      */
10     public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {
11         BufferedImage cutedImage = null;
12         CropImageFilter cropFilter = new CropImageFilter(x, y, width, height);  
13         Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter));  
14         cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
15         Graphics g = cutedImage.getGraphics();  
16         g.drawImage(img, 0, 0, null);  
17         g.dispose(); 
18         return cutedImage;
19     }

如果剪裁后需要保存剪裁得到的文件,使用ImageIO.write,參考上面把截圖保持為文件的代碼。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM