封装截图方法

  1. /**
  2. * 保存当前屏幕截图-生成的截图会按照截图的先后顺序生成有序的名称
  3. * @param fileName 图片名称,默认为.png格式,图片默认保存在screenShot目录下
  4. */
  5. public static String saveScreen(String fileName) {
  6. String imageName ;
  7. try {
  8. // 判断是否存在对应目录,不存在的话则创建
  9. File file = new File(TestConfig.SCREEN_SHOT_PATH);
  10. if (!file.exists() || !file.isDirectory()) {
  11. // 没有目录 创建截屏目录
  12. System.out.println("没有screenshot目录,创建目录");
  13. boolean isMkdirSucc = file.mkdir();
  14. if (isMkdirSucc) {
  15. System.out.println("创建screenshot目录成功");
  16. } else {
  17. System.out.println("创建screenshot目录失败");
  18. }
  19. } else {
  20. System.out.println("存在screenshot目录");
  21. }
  22. imageName = TestConfig.SCREEN_SHOT_PATH + File.separator + "_" + fileName + ".png";
  23. driver.saveScreenshot(imageName);
  24. return imageName;
  25. } catch (Exception e) {
  26. // TODO: handle exception
  27. ResultGenerator.fail("截屏异常", "", BaseErrorType.FUNCTION_FAILED);
  28. return null;
  29. }
  30. }

对元素截图

  1. /**
  2. * 元素截图
  3. * @param element
  4. * @param fileName
  5. * @throws InterruptedException
  6. */
  7. public static String screenForElement(Element element, String fileName) throws Exception {
  8. String filePath = saveScreen(fileName);
  9. File scrFile = new File(filePath);
  10. try {
  11. Point point = new Point();
  12. point.setLocation(element.getOriginX(),element.getOriginY());
  13. double width = element.getWidth();
  14. double height = element.getHeight();
  15. Rectangle rect = new Rectangle((int)width, (int)height);
  16. BufferedImage img = ImageIO.read(scrFile);
  17. BufferedImage dest = img.getSubimage(point.x, point.y, rect.width, rect.height);
  18. ImageIO.write(dest, "png", scrFile);
  19. driver.sleep(1000);
  20. return filePath;
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. return null;
  24. }
  25. }

快去尝试一下吧!