【发布时间】:2019-06-12 20:18:42
【问题描述】:
有没有办法在 Java 中获取 InputStream 的 HashCode,
我正在尝试使用 PrimeFaces 中的<p:fileUpload/> 上传图片,将其转换为 HashCode 并将其与另一张图片进行比较。
目前我正在尝试这个:
public void save(FileUploadEvent event) throws IOException {
HashCode hashCode = null;
HashCode hashCodeCompare = null;
hashCode = Files.asByteSource(new File(event.toString())).hash(Hashing.murmur3_128(50));
hashCodeCompare = Files.asByteSource(new File(FilePathOfFileToCompare)).hash(Hashing.murmur3_128(50));
boolean hashTrueFalse;
if(hashCode.equals(hashCodeCompare)) {
System.out.println("true");
} else{
System.out.println("false");
}
try (InputStream input = event.getFile().getInputstream()) {
String imageName = generateFileName() + "." + fileExtensions(event.getFile().getFileName());
String imageLink = PICTURE_DESTINATION + "\\" + imageName;
Picture picture = new Picture();
picture.setPictureUrl(imageLink);
pictureService.createOrUpdate(picture);
personForm.getCurrentPersonDTO().setPictureDTO(pictureMapper.toDTO(picture));
} catch (IOException e) {
e.printStackTrace();
}
}
有什么方法可以将InputStream 变成哈希码?
【问题讨论】:
-
等等,你是要获取流的HashCode还是图像的HashCode?你当然可以通过调用
.hashCode()来获取任何Java 对象的HashCode,但更重要的是int 代表什么以及为什么要使用它。 -
我尝试上传一张图片,并将其转为hashvalue,并与另一张图片进行比较,看是否已经存在。我尝试使用
.hashCode(),但如果我尝试将相同的图像与输入流和文件进行比较,它会给我一个不同的 hashCode -
如果您尝试使用 HashCode 来比较图像,如果图像是 JPG 或其他使用有损压缩存储的图像怎么办?图像文件位可能完全不同,但图像本身在功能上可能相同。
-
那么,您首选的比较图片上传和实际图片的方法是什么?我只需要一些来自外部的 iedeas/输入,因为我现在在这个问题上工作了 2.5 小时 D:
-
将 InputStream 读入 byte[] 然后在字节数组上运行哈希函数。您可能不想为此使用 hashCode() 。请改用 SHA256。
标签: java file hash inputstream guava