Monday, 6 January 2014

Image Comparision in Java(Can use with Selenium)

Sample Prog:-

package ASJ_IMG_CMP;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
import java.io.File;

class Image_CMP{
public static String imageComparison() {
System.out.println("Executing imageComparison");

try {

String file1 = "C:\\Documents and Settings\\amanjain\\Desktop\\1.PNG";
String file2 = "C:\\Documents and Settings\\amanjain\\Desktop\\2.PNG";

Image img1 = Toolkit.getDefaultToolkit().getImage(file1);
Image img2 = Toolkit.getDefaultToolkit().getImage(file2);

try {

PixelGrabber grab1 = new PixelGrabber(img1, 0, 0, -1, -1,false);
PixelGrabber grab2 = new PixelGrabber(img2, 0, 0, -1, -1,false);

int[] data1 = null;

if (grab1.grabPixels()) {
int width = grab1.getWidth();
int height = grab1.getHeight();
data1 = new int[width * height];
data1 = (int[]) grab1.getPixels();
}

int[] data2 = null;

if (grab2.grabPixels()) {
int width = grab2.getWidth();
int height = grab2.getHeight();
data2 = new int[width * height];
data2 = (int[]) grab2.getPixels();
}

System.out.println("Pixels equal: "
+ java.util.Arrays.equals(data1, data2));

if(java.util.Arrays.equals(data1, data2)==true){
    System.out.println("Both Images are Same");
}
else
    System.out.println("Both images are diffrent");

} catch (InterruptedException e1) {
e1.printStackTrace();
}
return "Pass";
} catch (Throwable t) {
// report error
return "Fail - " + t.getMessage();
}

}
public static void main(String args[]){
    imageComparison();
}
}

No comments:

Post a Comment