识别相同图片的Java代码
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();
}
}
作者:mervyn-hao
出处:https://www.cnblogs.com/mervyn-hao/p/17296856.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)