簡體   English   中英

在請求spring boot java中識別作為多部分文件出現的相同圖像

[英]Identifying the same image in coming as multipart file in request spring boot java

我正在創建一個帶有 spring boot 的應用程序,我正在對圖像進行 OCR。 我的請求要求提供多部分文件。 當我得到多部分文件時,我需要知道我是否已經處理過相同的圖像。

我創建了 MultipartEntity 和相同的哈希。 我相信下次如果出現相同的文件。 我將創建哈希並進行比較。

當我嘗試這樣做時。 我發現它的哈希值總是不同的。 有沒有一種方法可以識別此圖像以前是 OCR 的,因此僅基於散列我將檢索結果。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM