栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现屏幕截图及剪裁

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现屏幕截图及剪裁

Java标准API中有个Robot类,该类可以实现屏幕截图,模拟鼠标键盘操作这些功能。这里只展示其屏幕截图。

  截图的关键方法createScreenCapture(Rectangle rect) ,该方法需要一个Rectangle对象,Rectangle就是定义屏幕的一块矩形区域,构造Rectangle也相当容易:

new Rectangle(int x, int y, int width, int height),四个参数分别是矩形左上角x坐标,矩形左上角y坐标,矩形宽度,矩形高度。截图方法返回BufferedImage对象,示例代码:

   
   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) ,示例代码:

   
  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文档把。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152027.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号