最近开发自动化测试工具,要写图片验证码自动识别,识别过程首先要先进行图片验证码的截图,于是网上找了一些截图方法,但是我发现,大多数的截图方式都是先全屏截图,然后按元素在页面的位置和大小进行裁剪,这种方式有个弊端:全屏图片尺寸是按电脑屏幕分辨率来的,网页尺寸是前端代码设定的,这样会导致裁剪的位置不是理想位置
所以总结了一下截图方法:
方法一
全屏截图,然后裁剪,这种方式图片尺寸按电脑屏幕分辨率来的,与网页实际尺寸有差异,裁剪后的效果不好:
//截全屏图
File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//保存图片
try {
FileUtils.copyFile(sourceFile, new File(sourceImg + "img.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
//裁剪图片
BufferedImage img = null;
try {
img = ImageIO.read(new File(sourceImg + "img.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
int w = element.getSize().getWidth();
int h = element.getSize().getHeight();
Point point = element.getLocation();
//从元素左上角坐标开始,按照元素的高宽对img进行裁剪为符合需要的图片
BufferedImage dest = img.getSubimage(point.getX(), point.getY(), w, h);
try {
ImageIO.write(dest,"jpg", new File(sourceImg+"result.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
效果图(请忽略去除干扰的效果):
方法二
按元素截图:
//按元素截图
File sourceFile = element.getScreenshotAs(OutputType.FILE);
//保存图片
try {
FileUtils.copyFile(sourceFile, new File(sourceImg + "img.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
效果图: