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,参考上面把截图保持为文件的代码。

 

 

你可能感兴趣的:(java)