Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare screenshots to a reference image using appium

I am able to successfully take the screenshot one of the page of my application JainLibrary using below code. I am using junit and appium.

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

Now I want to compare the screenshot with a reference image so that I can move forward with the test case.

like image 328
Alex Avatar asked Oct 19 '22 09:10

Alex


1 Answers

A simple solution would be to compare each pixel with the reference screenshoot:

// 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");
}
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;
}

Note that you need to save the reference screenshot as a PNG. A JPEG format will alter the pixels.

like image 117
Florent B. Avatar answered Oct 21 '22 04:10

Florent B.