如何使用appium将屏幕截图与参考图像进行比较

Ale*_*lex 5 selenium automation android appium

我能够使用下面的代码成功地截取我的应用程序JainLibrary的页面之一.我正在使用junit和appium.

public String Screenshotpath = "Mention the folder Location";
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(Screenshotpath+"Any name".jpg"));
Run Code Online (Sandbox Code Playgroud)

现在我想将屏幕截图与参考图像进行比较,以便我可以继续使用测试用例.

Flo*_* B. 3

一个简单的解决方案是将每个像素与参考屏幕截图进行比较:

// save the baseline screenshot

driver.get("https://www.google.co.uk/intl/en/about/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\temp\\screenshot.png"));

// take another screenshot and compare it to the baseline

driver.get("https://www.google.co.uk/intl/en/about/");
byte[] pngBytes = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);

if (IsPngEquals(new File("c:\\temp\\screenshot.png"), pngBytes)) {
    System.out.println("equals");
} else {
    System.out.println("not equals");
}
Run Code Online (Sandbox Code Playgroud)
public static boolean IsPngEquals(File pngFile, byte[] pngBytes) throws IOException {
    BufferedImage imageA = ImageIO.read(pngFile);

    ByteArrayInputStream inStreamB = new ByteArrayInputStream(pngBytes);
    BufferedImage imageB = ImageIO.read(inStreamB);
    inStreamB.close();

    DataBufferByte dataBufferA = (DataBufferByte)imageA.getRaster().getDataBuffer();
    DataBufferByte dataBufferB = (DataBufferByte)imageB.getRaster().getDataBuffer();

    if (dataBufferA.getNumBanks() != dataBufferB.getNumBanks()) {
        return false;
    }

    for (int bank = 0; bank < dataBufferA.getNumBanks(); bank++) {
        if (!Arrays.equals(dataBufferA.getData(bank), dataBufferB.getData(bank))) {
            return false;
        }
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将参考屏幕截图保存为PNG. 格式JPEG会改变像素。