import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageCompare {
public static void main(String[] args) throws IOException {
File file1 = new File("image1.png");
File file2 = new File("image2.png");
BufferedImage img1 = ImageIO.read(file1);
BufferedImage img2 = ImageIO.read(file2);
int width1 = img1.getWidth();
int width2 = img2.getWidth();
int height1 = img1.getHeight();
int height2 = img2.getHeight();
if (width1 != width2 || height1 != height2) {
System.out.println("两张图片尺寸不同,肯定不相同");
} else {
long diff = 0;
for (int y = 0; y < height1; y++) {
for (int x = 0; x < width1; x++) {
int rgb1 = img1.getRGB(x, y);
int rgb2 = img2.getRGB(x, y);
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = (rgb1) & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = (rgb2) & 0xff;
diff += Math.abs(r1 - r2);
diff += Math.abs(g1 - g2);
diff += Math.abs(b1 - b2);
}
}
double n = width1 * height1 * 3;
double p = diff / n / 255.0;
if (p < 0.1) {
System.out.println("两张图片非常相似");
} else {
System.out.println("两张图片不相似");
}
}
}
}