java - 在请求spring boot java中识别相同的图像作为多部分文件
问题描述
我正在使用 spring boot 创建一个应用程序,我正在对图像进行 OCR。我的请求要求提供多部分文件。当我得到多部分文件时,我需要知道我是否已经处理过相同的图像。
我创建 MultipartEntity 和相同的哈希。我相信下次如果同样的文件来了。我将创建哈希并进行比较。
当我试图这样做时。我发现它的哈希值总是不同的。有没有一种方法可以识别该图像以前是 OCRed 的,因此仅基于哈希值我将检索结果。
Request params as file in request:-
@RequestParam("file") MultipartFile file
这就是我尝试创建哈希的方式:
FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);
String requestBodyHash = PanUtil.getHashFromRequestBody(multipartEntity.toString());
public static String getHashFromRequestBody(String req) {
String requestBodyHash = null;
try {
requestBodyHash = generateSha2FromPayload(req);
} catch (NoSuchAlgorithmException | URISyntaxException e) {
log.error("Exception occured while creating hash from request {}", e);
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, e.getMessage());
}
return requestBodyHash;
}
public static String generateSha2FromPayload(String json)
throws URISyntaxException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(json.getBytes(StandardCharsets.UTF_8));
return toHexString(digest);
}
解决方案
我已经使用下面的代码来找到图像的相同哈希值。
public static String toHexString(byte[] hash) {
// Convert byte array into signum representation
BigInteger number = new BigInteger(1, hash);
// Convert message digest into hex value
StringBuilder hexString = new StringBuilder(number.toString(16));
// Pad with leading zeros
while (hexString.length() < 32) {
hexString.insert(0, '0');
}
return hexString.toString();
}
调用这个函数。这将始终给出相同的十六进制。
toHexString(file.getBytes())
推荐阅读
- java - 我们如何加载其他语言数据而不是英语数据?
- typescript - @types/express 是否有任何文档?
- mysql - 如何仅在 MySQL 中使用日期值但 VARCHAR 数据类型的列中替换文本字符?
- python - 有界 sympy 符号变量
- c# - linq 语句的含义
- kubernetes-helm - 确保 Go 模板中的路径始终以斜杠结尾
- exiftool - 使用配置的 exiftool 将新标签写入 XMP 组不起作用
- excel - 在没有公式但保留设计的新工作簿中保存两个特定工作表
- javascript - Gatsby.js 图片源问题
- elasticsearch - Filebeat 的 KV 处理器