首页 > 解决方案 > 在请求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);
  }

标签: javaspring-boot

解决方案


我已经使用下面的代码来找到图像的相同哈希值。

  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())

推荐阅读