目前採用讀取圖片流並計算哈希值比對,效率較低。有無更高效的方法判斷兩張圖片是否為同一張?
public static boolean isSameImage(File f1, File f2) throws IOException {
if (f1.length() != f2.length()) return false;
// 可選:再比圖片寬高,需解碼圖片頭
try (FileInputStream in1 = new FileInputStream(f1);
FileInputStream in2 = new FileInputStream(f2)) {
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
int len1, len2;
while ((len1 = in1.read(buf1)) != -1) {
len2 = in2.read(buf2);
if (len1 != len2) return false;
for (int i = 0; i < len1; i++) {
if (buf1[i] != buf2[i]) return false;
}
}
return in2.read() == -1;
}
}