How to compare screenshots to a reference image using appium

前端 未结 1 1646
灰色年华
灰色年华 2021-01-13 03:01

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 Scre         


        
相关标签:
1条回答
  • 2021-01-13 03:14

    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.

    0 讨论(0)
提交回复
热议问题