All Products
Search
Document Center

AI Guardrails:Image OCR

Last Updated:Mar 31, 2026

Recognize text in images using Content Moderation SDK for Java. Submit a synchronous OCR task with the scenes parameter set to ocr, then parse the response to extract the recognized text.

Use cases

  • Identity verification: Extract text from ID cards and passports to verify user identity during onboarding.

  • Content filtering: Detect inappropriate or prohibited text embedded in user-uploaded images.

  • Automated data entry: Parse structured text from receipts, forms, or labels to reduce manual input.

  • License plate recognition: Extract vehicle plate numbers from traffic or security camera images.

Prerequisites

Before you begin, ensure that you have:

  • Java dependencies installed. See Installation for the required Java version. Using a different version causes operation call failures.

  • (For local images or binary image streams) The Extension.Uploader utility class downloaded and imported into your project.

Important

Use a RAM user's AccessKey ID and AccessKey secret instead of your Alibaba Cloud account credentials. Store credentials in environment variables rather than hardcoding them in your source code.

Submit synchronous OCR tasks

ImageSyncScanRequest submits synchronous OCR tasks. Set the scenes parameter to ocr to recognize text in images.

Supported regions

Region IDLocation
cn-shanghaiChina (Shanghai)
cn-beijingChina (Beijing)
cn-shenzhenChina (Shenzhen)
ap-southeast-1Singapore

How it works

  1. Initialize a client with your region and credentials.

  2. Build an ImageSyncScanRequest with scenes set to ["ocr"] and one task object per image.

  3. Call doAction() to submit the request synchronously.

  4. Parse the response: check the top-level code, iterate over data, and for each task result check suggestion and scene.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.*;

public class Main {

  public static void main(String[] args) throws Exception {
    // Initialize the client. Load credentials from environment variables.
    DefaultProfile profile = DefaultProfile.getProfile(
        "cn-shanghai",
        System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
        System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
    IAcsClient client = new DefaultAcsClient(profile);

    ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
    imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
    imageSyncScanRequest.setMethod(MethodType.POST);
    imageSyncScanRequest.setEncoding("utf-8");
    imageSyncScanRequest.setProtocol(ProtocolType.HTTP);

    JSONObject httpBody = new JSONObject();
    // Set scenes to "ocr" to recognize text in images.
    httpBody.put("scenes", Arrays.asList("ocr"));

    // Create one task per image. Submitting multiple images in one request
    // increases the average response time — the total time spans from request
    // initiation to when the last image is processed.
    JSONObject task = new JSONObject();
    task.put("dataId", UUID.randomUUID().toString());
    task.put("url", "https://example.com/xxx.jpg");  // Replace with your image URL
    httpBody.put("tasks", Arrays.asList(task));

    imageSyncScanRequest.setHttpContent(
        org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
        "UTF-8",
        FormatType.JSON);

    // Set timeouts. The server processes each image moderation request in up to 10 seconds.
    // A read timeout shorter than 10 seconds may cause timeout errors.
    imageSyncScanRequest.setConnectTimeout(3000);
    imageSyncScanRequest.setReadTimeout(10000);

    HttpResponse httpResponse = null;
    try {
      httpResponse = client.doAction(imageSyncScanRequest);
    } catch (ServerException e) {
      e.printStackTrace();
    } catch (ClientException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (httpResponse != null && httpResponse.isSuccess()) {
      JSONObject scrResponse = JSON.parseObject(
          org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
      System.out.println(JSON.toJSONString(scrResponse));

      int requestCode = scrResponse.getIntValue("code");
      JSONArray taskResults = scrResponse.getJSONArray("data");

      if (200 == requestCode) {
        for (Object taskResult : taskResults) {
          int taskCode = ((JSONObject) taskResult).getIntValue("code");
          JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");

          if (200 == taskCode) {
            for (Object sceneResult : sceneResults) {
              String scene = ((JSONObject) sceneResult).getString("scene");
              String suggestion = ((JSONObject) sceneResult).getString("suggestion");

              // When suggestion is "review" and scene is "ocr", the response
              // includes idCardInfo with the recognized text from the image.
              if ("review".equals(suggestion) && "ocr".equals(scene)) {
                JSONObject idCardInfo = ((JSONObject) sceneResult).getJSONObject("idCardInfo");
                System.out.println(idCardInfo.toJSONString());
              }
            }
          } else {
            // The individual image task failed. Check the task response for details.
            System.out.println("Task failed. Response: " + JSON.toJSONString(taskResult));
          }
        }
      } else {
        // The entire request failed. Check the response for error details.
        System.out.println("Request failed. Response: " + JSON.toJSONString(scrResponse));
      }
    }
  }
}

Request parameters

ParameterTypeDescription
scenesArrayModeration scenario. Set to ["ocr"] for text recognition.
dataIdStringUnique task identifier. Use UUID.randomUUID().toString() to generate one.
urlStringPublicly accessible URL of the image to moderate.

Response structure

The response is a JSON object with the following top-level fields:

FieldTypeDescription
codeIntegerRequest status code. 200 indicates success.
dataArrayArray of task results, one per submitted image.

Each element in data contains:

FieldTypeDescription
codeIntegerTask status code. 200 indicates the image was processed successfully.
resultsArrayArray of scene results.

Each element in results contains:

FieldTypeDescription
sceneStringModeration scenario. Returns ocr for OCR tasks.
suggestionStringModeration result. Valid values: pass, review, block.
idCardInfoObjectRecognized text from the image. Returned when suggestion is review and scene is ocr.

Usage notes

  • One task per image: Create a separate task object for each image. Submitting multiple images in one request extends the total response time — the server processes all images before returning results.

  • Timeouts: Set the read timeout to at least 10,000 ms (10 seconds). The server may take up to 10 seconds to process a single image moderation request.

  • Local images: To submit a local image or a binary image stream, download and import the Extension.Uploader utility class before submitting the request.

  • Credentials: Load your AccessKey ID and AccessKey secret from environment variables (ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET) to avoid exposing credentials in your code.

What's next

  • Installation — Set up the Content Moderation SDK for Java.