知識庫 / Spring / Spring Boot RSS 訂閱

使用 Spring Boot 從圖像中提取文本的 Amazon Textract

Cloud,Spring Boot
HongKong
11
11:03 AM · Dec 06 ,2025

1. 概述

企業經常需要從各種類型的圖像中提取有意義的數據,例如處理髮票或收據以進行費用跟蹤、身份文件以進行 KYC(瞭解您的客户)流程,或從表單中自動提取數據。然而,手動從圖像中提取文本既耗時又昂貴。

Amazon Textract 提供了一種自動化解決方案,它使用機器學習從文檔中提取印刷文本和手寫數據。

在本教程中,我們將探討如何在 Spring Boot 應用程序中使用 Amazon Textract 以提取圖像中的文本。 我們將逐步瞭解所需的配置並實現從本地圖像文件和 Amazon S3 存儲的圖像中提取文本的功能。

2. 設置項目

在開始從圖像中提取文本之前,我們需要包含 SDK 依賴項並正確配置我們的應用程序。

2.1. 依賴項

讓我們先將 Amazon Textract 依賴項 添加到我們項目的 pom.xml 文件中:

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>textract</artifactId>
    <version>2.27.5</version>
</dependency>

此依賴項為我們提供了 TextractClient 以及其他相關類,我們將使用它們與 Textract 服務進行交互。

2.2. 定義 AWS 配置屬性

現在,為了與 Textract 服務交互並從圖像中提取文本,我們需要配置我們的 AWS 憑據以進行身份驗證和 AWS 區域,以便使用該服務

我們將這些屬性存儲在項目的 application.yaml 文件中,並使用 @ConfigurationProperties 將值映射到 POJO,該 POJO 由服務層在與 Textract 交互時引用。

@Validated
@ConfigurationProperties(prefix = "com.baeldung.aws")
class AwsConfigurationProperties {
    @NotBlank
    private String region;

    @NotBlank
    private String accessKey;

    @NotBlank
    private String secretKey;

    // standard setters and getters
}

我們還添加了驗證註釋,以確保所有必需的屬性已正確配置。如果定義的驗證失敗,Spring ApplicationContext 將無法啓動。 這使我們能夠遵循“快速失敗”原則

以下是我們的 application.yaml 文件的片段,它定義了將自動映射到我們的 AwsConfigurationProperties 類的必需屬性:

com:
  baeldung:
    aws:
      region: ${AWS_REGION}
      access-key: ${AWS_ACCESS_KEY}
      secret-key: ${AWS_SECRET_KEY}

我們使用 ${} 屬性佔位符從環境變量中加載我們的屬性值。

因此,這種配置允許我們外部化 AWS 屬性並輕鬆地在我們的應用程序中訪問它們。

2.3. 聲明 TextractClient Bean

現在我們已經配置了屬性,接下來我們將使用它們來定義我們的 TextractClient Bean:

@Bean
public TextractClient textractClient() {
    String region = awsConfigurationProperties.getRegion();
    String accessKey = awsConfigurationProperties.getAccessKey();
    String secretKey = awsConfigurationProperties.getSecretKey();
    AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);

    return TextractClient.builder()
      .region(Region.of(region))
      .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
      .build();
}

TextractClient 類是與 Textract 服務進行交互的主要入口。 我們將在服務層中自動注入它,併發送請求以從圖像文件中提取文本。

3. 從圖像中提取文本

現在我們已經定義了 TextractClient Bean,接下來讓我們創建一個 TextExtractor 類並將其引用以實現我們預期的功能:

public String extract(@ValidFileType MultipartFile image) {
    byte[] imageBytes = image.getBytes();
    DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request
      .document(document -> document
        .bytes(SdkBytes.fromByteArray(imageBytes))
        .build())
      .build());
    
    return transformTextDetectionResponse(response);
}

private String transformTextDetectionResponse(DetectDocumentTextResponse response) {
    return response.blocks()
      .stream()
      .filter(block -> block.blockType().equals(BlockType.LINE))
      .map(Block::text)
      .collect(Collectors.joining(" "));
}

在我們的 extract() 方法中,我們將 MultipartFile 轉換為字節數組,並將其作為 Document 傳遞給 detectDocumentText() 方法。

Amazon Textract 目前僅支持 PNG、JPEG、TIFF 和 PDF 文件格式。 我們創建自定義驗證標註 @ValidFileType 以確保上傳的文件是這些支持的格式之一。

為了演示目的,在我們的輔助方法 transformTextDetectionResponse() 中,我們通過將每個 block 的文本內容連接起來,將 DetectDocumentTextResponse 轉換為一個簡單的 String。 但是,轉換邏輯可以根據業務需求進行自定義。

除了從我們的應用程序中傳遞圖像外,我們還可以從存儲在我們的 S3 桶中的圖像中提取文本:

public String extract(String bucketName, String objectKey) {
    textractClient.detectDocumentText(request -> request
      .document(document -> document
        .s3Object(s3Object -> s3Object
          .bucket(bucketName)
          .name(objectKey)
          .build())
        .build())
      .build());
    
    return transformTextDetectionResponse(response);
}

在我們的超載的 方法中,我們使用 S3 存儲桶名稱和對象鍵作為參數,從而指定圖像在 S3 中的位置。

需要注意的是,我們調用 bean 的 方法,這是一個同步操作,用於處理單頁文檔。 但對於處理多頁文檔,Amazon Textract 提供異步操作。

4. IAM 權限

為了使我們的應用程序正常運行,我們需要為我們應用程序中配置的 IAM 用户配置一些權限:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowTextractDocumentDetection",
            "Effect": "Allow",
            "Action": "textract:DetectDocumentText",
            "Resource": "*"
        },
        {
            "Sid": "AllowS3ReadAccessToSourceBucket",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

在我們的 IAM 策略中,AllowTextractDocumentDetection 語句允許我們調用 DetectDocumentText API 以從圖像中提取文本。

如果我們在 S3 中提取圖像中的文本,我們還需要包含 AllowS3ReadAccessToSourceBucket 語句,以允許讀取我們 S3 存儲桶的權限。

我們的 IAM 策略符合 最小權限原則,僅授予應用程序正確運行所需的必要權限

5. 結論

在本文中,我們探討了如何使用 Amazon Textract 與 Spring Boot 從圖像中提取文本。

我們討論瞭如何從本地圖像文件以及存儲在 Amazon S3 中的圖像中提取文本。

Amazon Textract 是一種功能強大的服務,在金融科技(fintech)和醫療科技(healthtech)行業得到廣泛應用,幫助自動化諸如處理髮票或從醫療表格中提取患者數據等任務。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.