您好我最近格式化了我的手机并将我的照片上传到了我的电脑,当我想将我的照片添加回手机时,我看到我有一些图像的多个副本。我想将我的所有照片合并到一个文件夹然后上传到我的手机,所以我写了一个java代码。
public class Main {
public static int imgCtr = 1;
public static File dest = new File("D:\\finalfinal");
public static void main(String[] args) throws Exception {
getContent("D:\\restoreFinal");
getContent("D:\\restore1");
getContent("D:\\restore2");
}
public static String getExtension(String fileName) {
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i + 1);
}
return extension;
}
public static boolean isImage(String extension) {
if (extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg")
|| extension.equalsIgnoreCase("png"))
return true;
return false;
}
public static boolean compareImages(File a, File b) throws Exception {
FileInputStream fisA = new FileInputStream(a);
FileInputStream fisB = new FileInputStream(b);
byte contentA[] = new byte[(int) a.length()];
byte contentB[] = new byte[(int) b.length()];
fisA.read(contentA);
fisB.read(contentB);
String strA = new String(contentA);
String strB = new String(contentB);
fisA.close();
fisB.close();
return strA.equals(strB);
}
public static void getContent(String path) throws Exception {
File source = new File(path);
ArrayList<File> content = new ArrayList<File>(Arrays.asList(source.listFiles()));
while (!content.isEmpty()) {
File f = content.get(0);
if (isImage(getExtension(f.getName()))) {
if (dest.listFiles().length == 0) {
Path p = Paths.get(dest + "\\i" + imgCtr + "." + getExtension(f.getName()));
imgCtr++;
Files.move(f.toPath(), p);
System.out.println(imgCtr);
} else {
File[] alreadyThere = dest.listFiles();
boolean match = false;
for (File cmp : alreadyThere) {
if (compareImages(f, cmp)) {
match = true;
break;
}
}
if (!match) {
Path p = Paths.get(dest + "\\i" + imgCtr + "." + getExtension(f.getName()));
imgCtr++;
Files.move(f.toPath(), p);
System.out.println(imgCtr);
}
}
}
content.remove(0);
}
}
}
我写的图像比较字符串比较,因为像素比较花了很长时间(有大约2k张照片)。但问题是它以某种方式复制了一张照片而没有任何差别,我可以看到。我搜索了源文件夹,但它任意复制照片,即使没有重复的照片在目标文件夹中也有重复。我怀疑它是关于比较方法,但找不到我的错误。
那么你能帮助我找出我的错误或建议一种快速,更可靠的方式来比较图像吗?
答案 0 :(得分:1)
如果图像尚未重新保存或未通过JPEG等有损文件格式,则可以比较像素。如果他们没有开始使用checksum comparison,那么只有当他们的校验和没有进行更广泛的像素比较时,尽管有损算法需要different approach。