import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class FindSameImages {
private static final int avgPixel = 128;
public static void main(String[] args) throws IOException {
String folder1 = "path/to/folder1";
String folder2 = "path/to/folder2";
List<String> folder1Images = new ArrayList<>();
List<String> folder2Images = new ArrayList<>();
getAllImageFiles(folder1, folder1Images);
getAllImageFiles(folder2, folder2Images);
Map<String, String> map = new HashMap<>();
for (String imagePath : folder1Images) {
String hash = getHash(imagePath);
map.put(hash, imagePath);
}
for (String imagePath : folder2Images) {
String hash = getHash(imagePath);
if (map.containsKey(hash)) {
String folderName = new File(map.get(hash)).getParentFile().getName();
System.out.println("相同图片:" + new File(imagePath).getName() + ",所在文件夹:" + folderName);
}
}
}
private static void getAllImageFiles(String folderPath, List<String> list) {
File folder = new File(folderPath);
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
getAllImageFiles(file.getAbsolutePath(), list);
} else if (isImageFile(file.getName())) {
list.add(file.getAbsolutePath());
}
}
}
private static boolean isImageFile(String fileName) {
String[] extensions = new String[] { "jpg", "jpeg", "png", "bmp", "gif" };
for (String ext : extensions) {
if (fileName.endsWith("." + ext)) {
return true;
}
}
return false;
}
public static String getHash(String imagePath) throws IOException {
BufferedImage image = ImageIO.read(new File(imagePath));
BufferedImage scaledImage = Scalr.resize(image, Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_EXACT, 8, 8, Scalr.OP_ANTIALIAS);
int[] pixels = new int[64];
int i = 0;
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
int rgb = scaledImage.getRGB(x, y);
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int b = rgb & 0xff;
int gray = (r + g + b) / 3;
pixels[i++] = gray;
}
}
StringBuilder sb = new StringBuilder();
for (int pixel : pixels) {
if (pixel > avgPixel) {
sb.append("1");
} else {
sb.append("0");
}
}
return sb.toString();
}
}