最近看了些别人写的代码,进行整合了下,主要是通过 appium 进行自动截图对比。

自动截图,并将图片保存至本地

public static void takeScreenShot1(AndroidDriver driver){  
   try {   
       String StrJ1 = "click";
       String StrJ2 = "swipe";
       if((StrJ1.equals(mstrHI))||(StrJ2.equals(mstrHI))){
           String p1="E:\\AutoScreenCapture1\\" + k  + "_"+ mstrHI + "_" + P1 +".jpg";
           File f1=driver.getScreenshotAs(OutputType.FILE);
           FileUtils.copyFile(f1,new File(p1)); 
           F1=new File(p1);
         //  System.out.println(F1);        
       }           
   }       
   catch (IOException e) {e.printStackTrace();}  
} 

获取本地已保存的文件

public static BufferedImage getImageFromFile(File f){
    BufferedImage img = null;   
    try {
        img = javax.imageio.ImageIO.read(f);
    }   
    catch (IOException e) {
        e.printStackTrace();
    }
    return img;
 }

进行图片对比

public static boolean sameAs(BufferedImage myImage,BufferedImage otherImage, double percent){
    if (otherImage.getWidth() != myImage.getWidth()) {  
       return false;    
    }
    if (otherImage.getHeight() != myImage.getHeight()) {
       return false;
    }
    int width = myImage.getWidth(); 
    int height = myImage.getHeight();   
    int numDiffPixels = 0;  
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
             if (myImage.getRGB(x, y) != otherImage.getRGB(x, y)) {
             numDiffPixels++;
             }
        }
    }   
    double numberPixels = height * width;   
    double diffPercent = numDiffPixels / numberPixels;  
    return percent <= 1.0D - diffPercent;
 }

获取图片对比结果

private static String getResult(AndroidDriver driver){
    Boolean same;
    String result=null;
    String StrJ1 = "click";
    String StrJ2 = "swipe";
    if((StrJ1.equals(mstrHI))||(StrJ2.equals(mstrHI))){
        try{
            BufferedImage img1=getImageFromFile(F1);
            BufferedImage img2=getImageFromFile(F2);
            same=sameAs(img1,img2,0.0);
            result = String.valueOf(same);

        }
        catch (Exception e) {e.printStackTrace();}  
    }
    return result;    
 }


↙↙↙阅读原文可查看相关链接,并与作者交流