package com.opslab.util.image;
import org.apache.log4j.Logger;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* 图片比较
*/
public final class ImageCompare {
private static Logger logger = Logger.getLogger(ImageCompare.class);
/**
* 改变成二进制码
*
* @param file
* @return
*/
public static String[][] getPX(File file) {
int[] rgb = new int[3];
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
String[][] list = new String[width][height];
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j);
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
list[i][j] = rgb[0] + "," + rgb[1] + "," + rgb[2];
}
}
return list;
}
/**
* 比较俩个图片的相似度
*
* @param image1
* @param image2
* @return
*/
public static float compareImage(File image1, File image2) {
String[][] list1 = getPX(image1);
String[][] list2 = getPX(image2);
int xiangsi = 0;
int busi = 0;
int i = 0, j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}
list1 = getPX(image1);
list2 = getPX(image2);
i = 0;
j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}
String baifen = "";
try {
baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + "");
baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3);
} catch (Exception e) {
baifen = "0";
}
if (baifen.length() <= 0) {
baifen = "0";
}
if (busi == 0) {
baifen = "100";
}
logger.debug("相似像素数量:" + xiangsi + " 不相似像素数量:" + busi + " 相似率:" + Integer.parseInt(baifen) + "%");
return Integer.parseInt(baifen);
}
}