Hi i recently formatted my phone and uploaded my photos to my pc, when i wanted to add my photos back to my phone i saw that i have multiple duplicates of some images. I wanted to merge all my photos into one folder then upload it to my phone so i wrote a java code.
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);
}
}
}
I wrote image compare with string compares because the pixel comparing took really long (had around 2k photos). But the problem is somehow it copies a photo multiple times without any difference i can see. And i searched for the source folders but it copies photos arbitrarily, even the photos that didn't have duplicates had duplicates in the destination folder. I doubt it is about the compare method, but couldn't find my mistake.
So can you help me find my fault or suggest a fast and more reliable way to compare images?