Image translation editor protocol

Updated at:

1. Core product features

1.1 Image processing features

The editor currently supports Image Translation Standard Edition, Image Translation Pro Edition, Smart Erasing Standard Edition, Smart Erasing Pro Edition, and Smart Matting. It also supports batch upload of images. After translating, erasing, or matting an image, you can use secondary editing on specific areas to create high-quality, multilingual marketing materials.

API

Core features

Batch image upload

Secondary editing

Image Translation Standard Edition

  • Translates images into multiple languages.

  • Supports brand term protection. When enabled, this feature prevents the translation of specified brand names.

  • Supports uploading a single image.

  • Supports batch uploads of up to 25 images at a time.

  • The editor holds a maximum of 25 images in total.

  • After translation, you can revert specific text segments to their original state.

  • You can translate any new text that you add.

  • You can add text, stickers, and assets for secondary editing.

Image Translation Pro Edition

Smart Erasing Standard Edition

Supports targeted erasing through various methods:

  • By element: transparent text blocks, specific names, text, and watermarks.

  • By text: Manually enter the text you want to erase.

  • You can add text, stickers, and assets for secondary editing.

Smart Erasing Pro Edition

  • One-click smart erasing requires no manual object selection.

  • The model automatically identifies objects to erase.

Smart Matting

  • After matting, you can set the background to a solid color or a transparent background.

1.2 Integration plans

This image editor offers two integration plans. Both plans use the same communication framework based on iframe and postMessage. They differ only in their capability routing and input parameters. Use the table below to choose the plan that best fits your business needs.

How to choose:

  • Choose Plan A if you need an all-in-one solution that combines multiple capabilities and keeps translation data within your business system.

  • Choose Plan B if you have already integrated the translation, matting, and erasing APIs and only need the editor for secondary editing of the results.

Dimension

Plan A: All-in-one image workbench

Plan B: Secondary editing

Positioning

An all-in-one workbench that integrates translation, matting, erasing, and editing capabilities into a single interface.

A two-stage "API + editor" model: first call the relevant APIs, then use the editor for secondary editing.

Typical use case

For end users who need a seamless workflow to process (translate, erase, mat) and edit images in a single interface.

After calling an API, users select specific images and use the editor to make final adjustments.

Data management

All processing and storage are handled within the integrator's workbench.

The API handles translation, erasing, and matting, while the editor is used only for secondary editing.

Composable capabilities

Basic capabilities: Choose one or more of the five processing capabilities.

Editing capabilities: Choose one or more options, including stickers, assets, and text.

General capabilities: Must include Original Comparison, undo, redo, download, and save. Optionally includes Back.

Billing method

Charges apply when you use the Image Translation Standard Edition, Image Translation Pro Edition, Smart Erasing Standard Edition, Smart Erasing Pro Edition, Smart Matting, or text translation capabilities.

1.3 Language support

The interface is available in Chinese (Simplified), English, Japanese, and Korean. The default language is Chinese. For more information, see section 3.3.6.

2. Product features

2.1 Core UI modules

Core module

Demo

Left console

  1. Five image processing capabilities

    • image translation

      • Standard

      • Pro

    • smart erase

      • Standard

      • Pro

    • AI cutout

image.pngimage.pngimage.png

Left console

  1. Upload area

  • Single-image upload area

  • Multi-image upload area

  • Image thumbnail list

image.pngimage.png

Pinned top bar

Common features

  • Back button

  • Image Editor

  • Task history

  • Text, sticker, asset

  • Compare with original

  • undo

  • redo

  • Download

  • Save

image.png

Right-side editing panel

image translation

image.png

smart erase Standard

smart erase Pro

AI cutout

None

Center canvas

  • Center canvas

  • Bottom task list

image.png

2.2 Editing state: Business rules

2.2.1 Image processing logic

  • Upload images

    • You can upload one or multiple images at a time, up to a maximum of 25.

    • The total number of images across all uploads cannot exceed 25.

  • Image processing: The processing buttons (e.g., "Translate", "Erase", "Cutout") apply to all uploaded images.

    • To process a single image, upload only one image.

    • To process multiple images, upload all desired images.

2.2.2 Image inheritance rules

  • Inheritance conditions: An image can be used for other functions if it meets the pixel and size requirements.

    • image translation

      • Formats: JPG, JPEG, PNG, BMP, WEBP

      • Dimensions: Width and height must be ≤ 4000 pixels.

      • Size: ≤ 10 MB

    • smart erase Standard & AI cutout

      • Formats: JPG, JPEG, PNG, BMP, WEBP

      • Dimensions: From 100×100 to 3000×3000 pixels

      • Size: ≤ 10 MB

    • smart erase Pro

      • Formats: JPG, JPEG, PNG, BMP, WEBP

      • Dimensions: From 256×256 to 3000×3000 pixels

      • Size: ≤ 10 MB

  • Inheritance triggers

    • After a successful upload, other functions inherit the original image, not the processed result.

  • Inheritance validation

    • The system validates the image against the requirements (pixel dimensions and file size) of the target function (translation, erase, or cutout).

      • If the image meets the requirements, inheritance is allowed.

      • If the image does not meet the requirements, the system displays the message: "Image does not meet the requirements. Please upload a compliant image."

2.2.3 Rules for further editing

  • Further editing is only supported for single images.

  • image translation

    • After a translation task completes successfully, the full editing panel appears on the right.

  • smart erase & AI cutout

    • The editing panel does not appear after you start a cutout or erase task.

    • If you use the Text, Sticker, or Asset tools after starting a cutout or erase task, their editing options appear on the right.

2.3 Product details

2.3.1 Processing: Translation, erase, and cutout

Functional area

Description

Demo

Capability configuration panel

Capability tab switching

Capability options:

  • image translation, including Standard and Pro versions

  • smart erase, including Standard and Pro versions

  • AI cutout

image.png

Left configuration panel

Main upload area

Common features applicable to all five capabilities

  • Batch upload support

    • Upload a single image.

    • Upload multiple images. You can upload up to 25 images at once, with a cumulative limit of 25.

  • UI styles

    • Single image

      • Displays the uploaded image. The "Re-upload" and "Delete" buttons remain visible.

    • Multiple images

      • Prompt text

        • Click to upload images

        • For upload requirements, see the inheritance rules above.

        • Upload progress: Shows the number of successfully uploaded images out of 25 (e.g., 9/25).

      • Display logic

        • When you upload a new batch of images, the main area displays the first image from that batch.

Single-image upload area⬇️

image.png

Multi-image upload area⬇️

image.png

Left configuration panel

Upload progress

  • Image validation

    • If an upload fails:

      • A notification is displayed.

    • If an upload succeeds:

      • Thumbnails of successful uploads appear below the upload area. You can hover over the list to navigate through the images.

      • Selecting a thumbnail displays that image in the main upload area.

image.png

Left configuration panel

image translation - Version

  • Version

    • Standard: Tooltip: "Cost-effective".

    • Pro: Tooltip: "More accurate translation".

image.png

image.png

Left configuration panel

image translation - Standard

  • Language

  • source language: Manual selection

  • target language: Manual selection

  • brand name protection

    • Icon tooltip: "When enabled, major brand names will not be translated."

    • Enabled by default.

image.png

Left configuration panel

image translation - Pro

  • Language

  • source language

    • Auto-detect is enabled by default, supporting 35 languages (see the Language Mapping in the "Common Scenarios" section).

    • Manual selection is also supported.

  • target language: Manual selection

  • brand name protection

    • Icon tooltip: "When enabled, major brand names will not be translated."

    • Enabled by default.

image.png

Left configuration panel

image translation - Translate button

  • Start Translation

    • Click to begin the translation process.

    • Applies to both Standard and Pro versions of image translation.

    • Charges apply upon successful translation.

image.png

Left configuration panel

smart erase - Version

  • Version

    • Standard: Tooltip: "Targeted erase".

    • Pro: Tooltip: "Automatic erase".

image.png

image.png

Left configuration panel

smart erase - Standard

Standard version

Element Erase, Area Erase, and Text Erase are mutually exclusive options.

  • Element Erase

    • Elements on main subject

      • Icon tooltip: "Only affects elements on the main subject. Elements outside the main subject are not modified."

      • Supports single and multiple selections. Unchecked by default.

        • Transparent text blocks

        • Specific names

        • Text

        • Visual clutter

    • Elements off main subject

      • Icon tooltip: "Only affects elements outside the main subject. Elements on the main subject are not modified."

      • Supports single and multiple selections. Unchecked by default.

        • Transparent text blocks

        • Specific names

        • Text

        • Visual clutter

  • Area erase

    • Icon tooltip: "Select an area on the original image to erase. When this mode is active, other erase methods (e.g., element erase) are disabled."

      • UI Implementation: Choose either Box Select or Lasso Select.

        • Box Select:

          • Tooltip: "Box Select"

          • You can only select one box at a time.

        • Lasso Select:

          • Tooltip: "Lasso Select"

          • You can only select one area at a time.

  • Text erase

    • Icon tooltip:

Specify text to be erased. You can enter multiple text strings, separated by commas.

When this mode is active, other erase methods (e.g., element erase) are disabled.

  • Text box

    • An example shows how to input multiple text strings.

      • Shows a character count for the input (e.g., 20/1000).

  1. Full UI - Standard version⬇️

image.png

  1. Tooltip for erasing elements on the main subject⬇️

image.png

  1. Tooltip for erasing elements off the main subject⬇️

image.png

  1. Tooltip for Area Erase⬇️

image.png

  1. Text Erase⬇️

image.png

smart erase - Pro

  • Pro version

    • Since image requirements differ for synchronous and asynchronous calls, the call logic is as follows:

      • All-in-one UI: Uses a synchronous call.

      • Two-stage UI: Uses either a synchronous or an asynchronous call.

    • Description: Automatically identifies elements to erase, such as transparent text blocks, specific names, text, and visual clutter.

image.png

smart erase - Erase button

  • Start Erasing

    • Click to start the erase process.

    • Note below the button: "This operation applies to all uploaded images."

    • Applies to both Standard and Pro versions of smart erase.

    • Charges apply upon successful erase.

image.png

Left configuration panel

AI cutout

  • Background Color (select one)

    • Solid Color

      • Defaults to a white background.

        • You can select a different target color using the color picker.

    • Transparent

  • Output Dimensions

    • Image Width

      • Input range: 100–3000

    • Image Height

      • Input range: 100–3000

  1. Full UI⬇️

image.png

  1. When Solid Color is selected⬇️

image.png

Click the background color swatch to open the color picker.

image.png

  1. When Transparent background is selected⬇️

image.png

Start Cutout

  • Click to start the cutout process.

  • Charges apply upon successful cutout.

image.png

Processing state

Task list

Common features applicable to all five capabilities

  • The task list appears after you upload images and run a translation, cutout, or erase task.

UI Style

  • Position: The task list is located at the bottom of the canvas and can display up to 25 images.

  • Processing status filter

    • One of the "Succeeded" or "Failed" filters is always active.

    • "Succeeded" is selected by default.

    • The "Succeeded" and "Failed" filters are mutually exclusive.

  • Viewing images: If there are many images, use the scrollbar to browse and select the target image.

  • Selecting an image: Click an image thumbnail to display it on the main canvas.

  • Deleting an image:

    • You can delete images individually from either list; batch deletion is not supported.

    • The delete icon appears on hover.

Full UI⬇️

image.png

Failed state⬇️

image.png

Processing state

Full UI

image translation Standard

image.png

Processing state

Full UI

image translation Pro

image.png

Processing state

Full UI

smart erase Standard

image.png

Processing state

Full UI

smart erase Pro

image.png

Processing state

Full UI

AI cutout

image.png

Completed state

Save

Common feature applicable to translation, cutout, and erase functions.

image.png

Download

Common feature applicable to translation, cutout, and erase functions.

Unsaved changes pop-up

Common feature applicable to all functions. A confirmation pop-up appears if you try to navigate to the previous page before saving or downloading your work.

image.png

Task history

Tasks

Click the "Task history" button to view successfully processed tasks.

  • Data display rules

    • A task is logged after you perform a translation, erase, or cutout operation and click Save or Download.

    • Tasks with a single image can be viewed directly.

    • For multi-image tasks, click the task to view its images.

    • Tasks are displayed in reverse chronological order.

    • You can filter tasks by any of the five capabilities, with both single and multiple selections supported.

Click "Task history" in the top bar⬇️

image.png

In task history, you can filter the results⬇️

image.png

2.3.2 Further editing capabilities

Editing capability type

Description

Demo

Common editing capabilities

Applies to image translation (Standard and Pro), smart erase (Standard and Pro), and AI cutout.

  • Text: Always available. Enters editing mode after image processing.

    • Click to add custom text.

    • You can translate or edit the added text further (e.g., font size, font family, font weight).

  • Sticker: Always available. Enters editing mode after image processing.

    • The platform provides a sticker library.

    • Added stickers can be edited further (e.g., color, opacity, text).

  • Asset: Always available. Enters editing mode after image processing.

    • You can upload assets from your local device.

    • Assets can be edited further (e.g., color, opacity, tilt angle).

Add Text - Input custom text⬇️

image.png

Add Sticker - Use the platform's sticker library⬇️

image.png

Add Asset - Upload an asset from your local device⬇️

image.png

Specific editing capabilities

Applies only to image translation (Standard and Pro).

  • Editing panel display rules

    • The editing options highlighted in the red box (in the demo on the right) appear only after running an image translation task.

  • Translate text

    • Enabled by default.

    • You can restore individual text boxes to their pre-translation state.

  • Translation language selection

    • After selecting a text segment, you can re-translate it by choosing a new source and target language.

  • Translate button

    • Clicking this button initiates text translation. Charges apply upon successful translation.

  • Restore Original

    • Click to revert the text to its pre-translation state.

image.png

3. Access method

3.1 Overall workflow

  1. The client sends a request to the server, for example, POST /api/aidge-editor/access-url.

  2. Based on the current user's identity, the server requests a one-time key from the Alibaba Cloud authentication service and constructs the complete iframe URL.

  3. The server returns the complete iframe URL to the client.

  4. The client creates or refreshes an iframe and sets its src attribute to the received URL.

  5. The Alibaba Cloud authentication service validates the key. Upon successful validation, the editor page loads.

  6. Once the editor page loads, it sends a load completion event to the parent page using postMessage.

  7. Upon receiving the load completion event, the client sends an initialization event with the required parameters to the iframe using postMessage.

We recommend that the server return the complete iframe URL directly to reduce the risk of client-side assembly errors and minimize key exposure. Alternatively, the server can return only the key, allowing the client to construct the iframe URL immediately upon receipt.

To ensure data isolation between your users, pass a unique user ID to the RoleSessionName field. For details, see the Java code example in section 3.2.6.

3.2 Server-side integration

For implementation details, see federated access.

3.2.1 Create a RAM user and grant permissions

If the RAM user already exists, skip this step.

3.2.2 Grant AliyunSTSAssumeRoleAccess

image.png

3.2.3 Create a RAM role

Sign in to the console with your Alibaba Cloud account and create a RAM role. You can also create the role by calling the CreateRole API.

image.png

image.png

image.png

3.2.4 Attach a permission policy

Search for "Aidge" and select the corresponding permission policy.

image.png

3.2.5 Obtain Role ARN, AccessKey ID, and AccessKey Secret

image.png

image.png

image.png

3.2.6 Java sample code

<dependencies>
      <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>aliyun-java-sdk-sts</artifactId>
          <version>3.0.0</version>
      </dependency>
      <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>aliyun-java-sdk-core</artifactId>
          <version>3.5.0</version>
      </dependency>
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.5</version>
      </dependency>
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.47</version>
      </dependency>
</dependencies>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * Sample of federated access to the Aidge virtual ISP console.
 * <p>
 * Flow: Call AssumeRole to get temporary credentials -> Call GetSigninToken to get a signin token -> Construct the federation sign-in URL.
 */
public class Test {

    private static final String SIGN_IN_DOMAIN = "https://signin.aliyun.com/federation";

    /**
     * Gets a signin token by using temporary credentials (an AccessKey pair and a security token).
     * https://www.alibabacloud.com/help/doc-detail/91913.html
     *
     * @param accesskeyId
     * @param accessKeySecret
     * @param securityToken
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private static String getSignInToken(String accesskeyId, String accessKeySecret, String securityToken)
            throws IOException, URISyntaxException {
        URIBuilder builder = new URIBuilder(SIGN_IN_DOMAIN);

        builder.setParameter("Action", "GetSigninToken")
                .setParameter("AccessKeyId", accesskeyId)
                .setParameter("AccessKeySecret", accessKeySecret)
                .setParameter("SecurityToken", securityToken)
                .setParameter("TicketType", "mini");

        HttpGet request = new HttpGet(builder.build());
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try (CloseableHttpResponse response = httpclient.execute(request)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String context = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(context);
                return jsonObject.getString("SigninToken");
            } else {
                System.out.println(response.getStatusLine());
            }
        }
        return null;
    }

    private static String getChatbotLoginUrl(String pageUrl, String signInToken) throws URISyntaxException {
        URIBuilder builder = new URIBuilder(SIGN_IN_DOMAIN);
        builder.setParameter("Action", "Login");
        // The URL to redirect to after the session expires. Typically, this is a URL on your web server that handles 302 redirects.
        builder.setParameter("LoginUrl", "https://signin.aliyun.com/login.htm");
        // The actual Aidge console page to access, such as the home page or editor page.
        builder.setParameter("Destination", pageUrl);
        builder.setParameter("SigninToken", signInToken);
        HttpGet request = new HttpGet(builder.build());
        return request.getURI().toString();
    }

    /**
     * Obtains temporary credentials from Security Token Service (STS) by calling the AssumeRole API.
     * See https://www.alibabacloud.com/help/doc-detail/28763.html
     *
     * @param roleArn         The Alibaba Cloud Resource Name (ARN) of the RAM role. Format: acs:ram::<Alibaba Cloud account ID>:role/<Role name>
     * @param accessKeyId     The AccessKey ID of the caller.
     * @param accessKeySecret The AccessKey Secret of the caller.
     * @param roleSessionName A custom session name for user-level access auditing. Format: ^[a-zA-Z0-9\.@\-_]+$
     * @return
     * @throws ClientException
     */
    private static AssumeRoleResponse.Credentials assumeRole(String roleArn, String accessKeyId,
                                                             String accessKeySecret, String roleSessionName)
            throws ClientException {
        String defaultRegion = "cn-hangzhou";
        IClientProfile profile = DefaultProfile.getProfile(defaultRegion, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        // Use the constructed Role ARN directly.
        request.setRoleArn(roleArn);
        // A custom parameter to differentiate between tokens, useful for user-level access auditing. Format: ^[a-zA-Z0-9\.@\-_]+$
        request.setRoleSessionName(roleSessionName);
        // The expiration time in seconds. Valid values: 900 to 3600. Default: 3600.
        request.setDurationSeconds(3600L);
        AssumeRoleResponse response = client.getAcsResponse(request);
        return response.getCredentials();
    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        try {
            /*
             * Step 0: Prepare a RAM user and grant the required permissions.
             */
            // The ARN of the RAM role to assume, constructed from your Alibaba Cloud account ID and role name. Replace with your actual value: acs:ram::${accountId}:role/${roleName}
            String roleArn = "Replace with your actual value";
            // The AccessKey ID and AccessKey Secret of the RAM user, which must have the AliyunSTSAssumeRoleAccess permission. Replace with your actual values.
            String accessKeyId = "Replace with your actual value";
            String accessKeySecret = "Replace with your actual value";

            // The user ID from your business system. This helps distinguish between different business users under the same RAM role, which is useful for access auditing.
            // We recommend using a unique identifier from your business system, such as a user ID. The format must match ^[a-zA-Z0-9.@-_]+$ and the length must be 2 to 64 characters.
            String userId = "Replace with your actual value";

            /*
             * Step 1: Get temporary credentials by calling the AssumeRole API.
             */
            AssumeRoleResponse.Credentials credentials =
                    assumeRole(roleArn, accessKeyId, accessKeySecret, userId);

            System.out.println("Expiration: " + credentials.getExpiration());
            System.out.println("Access Key Id: " + credentials.getAccessKeyId());
            System.out.println("Access Key Secret: " + credentials.getAccessKeySecret());
            System.out.println("Security Token: " + credentials.getSecurityToken());
            System.out.println("RoleSessionName: " + userId);

            /*
             * Step 2: Get the signin token.
             */
            String signInToken = getSignInToken(credentials.getAccessKeyId(),
                    credentials.getAccessKeySecret(),
                    credentials.getSecurityToken());

            System.out.println("Your SigninToken is: " + signInToken);

            // Integrate the Aidge editor page.
            String pageUrl = "https://ecoa4service.console.aliyun.com/editor";

            String accessUrl = getChatbotLoginUrl(pageUrl, signInToken);
            System.out.println("Your PageUrl is : " + accessUrl);
        } catch (ClientException e) {
            System.out.println("Failed:");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
    }
}

3.2.7 Signin token generation requirements

  • The signin token generation logic must be deployed on the server. The server must securely store sensitive information such as the AccessKey ID, AccessKey Secret, and Role ARN.

  • Generate a new signin token each time you open the editor page.

  • Do not persist the signin token as a long-term credential. If you need to log information for auditing, record only the necessary audit information and avoid exposing the signin token in plaintext in frontend logs, NGINX access logs, or monitoring systems.

  • Use the signin token immediately after generation. The signin token is valid for 30 seconds and can be used only once.

  • If you refresh or reopen the page, or revisit the URL after copying the link, run the server-side signin token generation flow again.

3.3 Client-side access

To embed the editor in the page, use an <iframe> tag and set its src attribute to the address returned by the server. For details, refer to Section 3.2 above.

The customer front-end communicates with the editor via postMessage. The editor's origin is https://ecoa4service.console.aliyun.com. To ensure secure communication, we recommend specifying this origin when sending messages and verifying it when receiving them. See section 3.3.7 for more details.

When the client receives the pageReady message from the editor iframe, it can initialize the editor by sending it a message with the action property set to init.

window.addEventListener("message", (ev: MessageEvent) => {
  const { action } = ev.data ?? {};

  if (action === "pageReady") {
    iframeEle.contentWindow?.postMessage(
      {
        action: "init",
        data: {
          tool: "translate",
        },
      },
      editorOrigin,
    );
  }
});

3.3.1 Editor initialization parameters

No.

Parameter

Field

Type

Required

Default

Description

1

editor capability

tool

string/string[]

Yes

-

Defines which editor capabilities to enable. Pass a single string for one capability, or a string array for multiple capabilities. When you enable multiple capabilities, tabs appear at the top of the editor to switch between them.

translate: image translation standard edition

translatePro: image translation Pro edition

translateBoth: Enables both standard and Pro editions of image translation, allowing users to switch between editions in the editor.

erase: smart erase standard edition

erasePro: smart erase Pro edition

eraseBoth: Enables both standard and Pro editions of smart erase, allowing users to switch between editions in the editor.

matting: smart matting

The array must contain one value from each capability group. For example: ["translateBoth","eraseBoth","matting"].

2

image URL

imageUrl

string/string[]

No

-

The URL of the image that you want to translate. In batch mode (uploadMode=multi), you can pass an array to preset multiple images. Do not directly use image links from e-commerce platforms that restrict image access. We recommend that you back up the images and then pass their URLs. If you do not provide a URL, you can manually upload images in the editor.

3

upload mode

uploadMode

string

No

"single"

"single": Allows uploading only one image. "multi": Allows batch uploads. The maxImages parameter sets the maximum number of images.

4

batch limit

maxImages

number

No

25

This parameter takes effect only when uploadMode="multi". The valid range is 1 to 25. If the value is outside this range or invalid, it defaults to 25.

5

source language

sourceLanguage

string

No

-

If this parameter is not provided, you can select the source language manually in the editor. For a list of supported languages, see §7.1.

6

target language

targetLanguage

string

No

-

If this parameter is not provided, you can select the target language manually in the editor. For a list of supported languages, see §7.1.

7

interface language

lang

string

No

"zh-cn"

The UI language of the editor. Options: zh-cn / en-us / ja-jp / ko-kr. After loading, you can still dynamically switch the language by using the switch-language message (see §3.3.6).

8

Default state for "preserve original text" (brand/product names)

includingProductAreaDefaultValue

boolean

No

true

true: Enables the "preserve original text (brand names)" option by default.

false: Disables the "preserve original text (brand names)" option by default.

9

re-editing

reEdit

boolean

No

false

true: Directly edits the translated image without displaying the left-side upload panel or history. You must also pass the translated layer information reEditData.

false: Displays the left-side upload panel and history.

10

re-editing data

reEditData

string

No

''

The result data of a processed image, which includes layer information. You can get this data from an API response.

11

charge interception

charge

boolean

No

false

true: When a user clicks "Translate Now," the editor sends a message to the iframe's host page. The actual API call is executed only after receiving a confirmation message from the host. This allows the integrator to control paid API calls.

false: The editor executes the API call immediately when the user clicks "Translate Now."

12

charge interception (text translation)

chargeTextTranslation

boolean

No

false

Production interception for Text Translation on the right-side panel is independent of charge. When enabled, the host must handle the biz="textTranslation" case for the generate event and send back a respond. It is disabled by default for compatibility with legacy integrators. Note: Text Translation does not support self-invocation by the host (no corresponding applyToolResult). Even if enableToolExecution=false, the system only waits for a respond.

13

tool execution

enableToolExecution

boolean

No

true

true: When a user clicks 'Translate Now', the corresponding API is called, the task history is recorded, and the 'History' button is displayed. false: The API is not called, the task history is not recorded, and the 'History' button is hidden. The integrator can call the translation API independently and use the applyToolResult message to send the result back to the editor. For more information, see section 4.3.

14

editor UI configuration

editorConfig

object

No

{}

For each sub-option, custom values from the integrator take precedence. If a sub-option is not provided, its default value is used.

3.3.2 editorConfig parameters

The following configuration items are optional. They are grouped by capability, and items for disabled capabilities are ignored. The empty string '' is a significant value: setting any Tip field to '' hides its tooltip; for a single-tier entry point, setting the tier label to '' hides that label.

General configuration

No.

Name

Parameter

Type

Default

Description

1

Back button visibility

showBack

boolean

false

true: Shows the back button. Clicking it sends a back message.

false: Hides the back button.

2

Sidebar title

editorTitle

string

"Image Editor"

Title at the top of the sidebar.

3

History button visibility

showHistory

boolean

true

When false, hides the history button and its icon.

4

History button text

historyButtonText

string

"History"

-

5

History panel title

historyPanelTitle

string

"Task History"

-

6

Upload button text

imageUploaderButtonText

string

"Click to upload image"

-

7

Add text button visibility

showAddText

boolean

true

true: Shows the Add text button.

false: Hides the Add text button.

8

Add sticker button visibility

showAddSticker

boolean

true

true: Shows the Add sticker button.

false: Hides the Add sticker button.

9

Add asset button visibility

showAddImage

boolean

true

true: Shows the Add asset button.

false: Hides the Add asset button.

Image translation (Standard and Pro)

No.

Name

Parameter

Type

Default

Description

10

'Image translation' panel title

imageTransPanelTitle

string

"Image translation"

-

11

'Standard' label text

imageTransLabel

string

"Standard"

When tool=translate, it is displayed to the right of the title but is not displayed if set to ''. When tool=translateBoth, it is displayed below the image upload area, is always displayed even if set to '', and also serves as the type label for task history.

12

'Pro' label text

imageTransProLabel

string

"Pro"

When tool=translatePro, it is displayed to the right of the title. It is not displayed if set to ''. When tool=translateBoth, it is displayed below the image upload area, even if set to '', and is also used as the type label for task history.

13

'Standard' tooltip text

imageTransTip

string

"Cost-effective"

Set to '' to hide the tooltip.

14

'Pro' tooltip text

imageTransProTip

string

"More accurate translation"

Set to '' to hide the tooltip.

15

'Language' section title

imageTransOptionsTitle

string

"Language"

-

16

'Source language' label text

sourceLanguageLabel

string

"Source language"

-

17

'Source language' tooltip text

sourceLanguageTip

string

"The original language of the content"

Set to '' to hide the tooltip.

18

'Target language' label text

targetLanguageLabel

string

"Target language"

-

19

'Target language' tooltip text

targetLanguageTip

string

"The language to translate the content into"

Set to '' to hide the tooltip.

20

'Brand name protection' label text

includingProductAreaLabel

string

"Brand name protection"

-

21

'Brand name protection' tooltip text

includingProductAreaTip

string

"When enabled, this feature prevents the translation of major brand names."

Set to '' to hide the tooltip.

22

Brand name protection default value

includingProductAreaDefaultValue

boolean

true

true: The switch is on by default.

false: The switch is off by default.

23

'Translate' button text

imageTransButtonText

string

"Translate"

-

24

'Translate text' switch label

translateTextLabel

string

"Translate text"

Only the label text is configurable; the switch's functionality remains unchanged.

Smart erase - Standard

No.

Name

Parameter

Type

Default

Description

25

Smart erase panel title

erasePanelTitle

string

"Smart erase"

-

26

"Standard" label text

eraseLabel

string

"Standard"

Set to '' to hide the label when only a single version is available.

27

"Pro" label text

eraseProLabel

string

"Pro"

Set to '' to hide the label when only a single version is available.

28

"Standard" tooltip text

eraseTip

string

"Designated Erase"

Set to '' to hide the tooltip.

29

"Pro" tooltip text

eraseProTip

string

"Automatic Erase"

Set to '' to hide the tooltip.

30

Main object erase entry

showEraseObject

boolean

true

Shows or hides the entry for erasing the main object. This feature is available only in the Standard version.

true: Shows the entry.

false: Hides the entry.

31

Non-main object erase entry

showEraseNonObject

boolean

true

Shows or hides the entry for erasing non-main objects. This feature is available only in the Standard version.

true: Shows the entry.

false: Hides the entry.

32

Area erase entry

showEraseArea

boolean

true

Shows or hides the entry for area erase (box or lasso select). This feature is available only in the Standard version.

true: Shows the entry.

false: Hides the entry.

33

Text erase entry

showEraseText

boolean

true

Shows or hides the entry for erasing specified text. This feature is available only in the Standard version.

true: Shows the entry.

false: Hides the entry.

34

Erase button text

eraseButtonText

string

"Start Erasing"

-

Intelligent matting

No.

Name

Parameter

Type

Default

Description

35

Intelligent matting panel title

mattingPanelTitle

string

"Intelligent Matting"

-

36

'Background type' label

mattingBgLabel

string

"Background Type"

-

37

'Solid color' option label

mattingBgWhiteLabel

string

"Solid Color"

-

38

'Transparent' option label

mattingBgTransparentLabel

string

"Transparent"

-

39

Default background

mattingBgDefaultValue

string

"white"

Enum value: "white" (Default: solid color background, opens the color picker) / "transparent" (Transparent background).

40

'Output size' group title

mattingSizeLabel

string

"Output Size"

-

41

Label for the 'target width' field

mattingWidthLabel

string

"Target Width"

-

42

Label for the 'target height' field

mattingHeightLabel

string

"Target Height"

-

43

Text on the intelligent matting button

mattingButtonText

string

"Start Matting"

-

3.3.3 Editor message body

Messages sent from the editor using postMessage have the following structure:

{
  biz: "translate",
  action: "generate",
  data: {
    imageNum: 1,
  },
}

The following table describes the fields in the message body.

Parameter

Value

Required

Description

biz

"translate"

No

This is the business identifier. The value is "translate" for the image translation standard edition and "translatePro" for the image translation pro edition.

action

"generate"

Yes

The message type.

data

{ imageNum: 1 }

No

The message data.

3.3.4 Editor error message

The editor sends error messages via postMessage with the following message body structure:

{
  biz: "translate",
  action: "error",
  errCode: "translate-taskError",
  errMessage: errMsg,
}

The following table describes the fields in the error message body.

Parameter

Example value

Required

Description

biz

"translate"

Yes

The business identifier associated with the error.

action

"error"

Yes

The message type, which is always "error" for error messages.

errCode

"translate-taskError"

Yes

A unique code that identifies the error. For example, "translate-taskError" indicates that the translation failed.

errMessage

errMsg

Yes

A human-readable description of the error.

Integrators can use errCode to display custom error messages.

3.3.5 Messages sent by the editor

Communication direction: editor iframe → client frontend

action

Trigger

Message body

Key data

Related message

pageReady

The editor page has loaded.

{ action: "pageReady" }

No other fields.

The client frontend responds with an init message.

back

The user clicks the back button when editorConfig.showBack is true in the initialization configuration.

{ action: "back" }

No other fields.

-

generate

The user initiates a paid API call when charge is true in the initialization configuration.

{ biz, action: "generate", data }

data.imageNum: Number of images to generate.

data.params: The parameters for this call.

The client frontend must respond with a respond message.

error

An editor operation fails.

{ biz, action: "error", errCode, errMessage }

errCode: Error code.

errMessage: Error message.

For more information, see section 3.3.4.

-

taskSuccess

A generation task completes successfully.

{ biz, action: "taskSuccess", data }

data: ResultItem[]

For more information, see section 5.1.

-

submitAll

The user clicks Save or Download, or the editor responds to a requestResult message.

{ biz, action: "submitAll", data }

data: ResultType[]

For more information, see section 5.3.

Triggered by a requestResult message.

3.3.6 Messages the editor can receive

Communication direction: client frontend → editor iframe

action

Trigger

Message body

Key data

Editor action

init

After the client frontend receives pageReady.

{ action: "init", data }

data.tool: Specifies the editor's capabilities. This field is required.

For more information, see section 3.3.1.

Initializes the editor based on the configuration.

switch-language

When the UI language needs to be switched at runtime.

{ action: "switch-language", lang }

lang: The target language. Valid values are zh-cn, en-us, ja-jp, and ko-kr.

Switches the UI language dynamically without reloading the page.

respond

After the client frontend receives generate.

{ biz, action: "respond", success }

biz: Must be consistent with generate.biz.

success: true: Continues the generation process.

success: false: Aborts the generation process.

For more information, see section 4.1.

Determining whether to execute a paid API call based on success

applyToolResult

After the client frontend completes the API call.

{ biz, action: "applyToolResult", data }

biz: Must be consistent with generate.biz.

data: The result data from the API call.

For more information, see section 4.3.

Loads and displays the result.

requestResult

When the client frontend needs to retrieve the complete current result.

{ action: "requestResult" }

No other fields.

For more information, see section 5.1.

Returns the complete result in a submitAll message.

Example client-side code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Aidge Editor Integration Example</title>

    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        margin: 0;
      }

      #editorIframe {
        display: block;
        width: 100%;
        height: 100%;
        border: 0;
      }
    </style>
  </head>

  <body>
    <iframe
      id="editorIframe"
      title="Aidge Online Editor"
      allow="clipboard-read; clipboard-write"
      ></iframe>

    <script>
      const editorIframe = document.getElementById("editorIframe");

      // The origin of the editor page, used for validating and sending postMessage.
      const editorOrigin = "https://ecoa4service.console.aliyun.com";

      // The initialization parameters for the editor. Replace the example values to match your business requirements.
      const editorInitData = {
        // translate: image translation standard edition
        // translatePro: image translation Pro edition
        // translateBoth: Standard + Pro editions, allowing you to switch between them in the editor.
        tool: "translateBoth",

        // The following three properties are optional. If `imageUrl` is omitted, you can upload images manually in the editor.
        imageUrl: "https://example.com/source.jpg",
        sourceLanguage: "zh",
        targetLanguage: "en",

        // Enable production interception. After the editor sends a 'generate' message, it waits for the parent page to return a 'respond' message.
        charge: true,

        // The editorConfig object and all its sub-options are optional.
        editorConfig: {
          editorTitle: "Image Editor",
          showHistory: true,
          historyButtonText: "History",
          imageTransPanelTitle: "Image Translation",
          historyPanelTitle: "Task history",
          imageUploaderButtonText: "Click to upload image",
          imageTransLabel: "Standard",
          imageTransProLabel: "Pro",
          imageTransTip: "Cost-effective",
          imageTransProTip: "More accurate translation",
          imageTransOptionsTitle: "Language",
          sourceLanguageLabel: "Source language",
          sourceLanguageTip: "The language of the content to be translated",
          targetLanguageLabel: "Target language",
          targetLanguageTip: "The language you want to translate the content into",
          includingProductAreaLabel: "Keep Original Text (Brand Name)",
          includingProductAreaTip: "If enabled, mainstream brand names will not be translated",
          includingProductAreaDefaultValue: true,
          imageTransButtonText: "Start Translation",
          showAddText: true,
          showAddSticker: true,
          showAddImage: true
        }
      };

      /**
     * Determines whether to allow this paid API call.
     * In a real-world integration, call your server-side here to verify the user's balance or permissions.
     */
      async function checkGenerationPermission({ biz, imageNum, data }) {
        console.log("Production request pending confirmation:", {
          biz,
          imageNum,
          data
        });

        // TODO: Return the validation result according to your business logic.
        return true;
      }

      /**
     * Handles a production interception request.
     */
      async function handleGenerate(message) {
        const { biz, data } = message;
        const { imageNum } = data ?? {};
        let success = false;

        try {
          success = await checkGenerationPermission({
            biz,
            imageNum,
            data
          });
        } catch (error) {
          console.error("Production request check failed:", error);
        }

        // The `biz` field must match the value from the editor's `generate` message.
        editorIframe.contentWindow.postMessage(
          {
            biz,
            action: "respond",
            success
          },
          editorOrigin
        );
      }

      /**
     * Handles an editor error.
     */
      function handleEditorError(message) {
        const { biz, errCode, errMessage } = message;

        console.error("Editor error:", {
          biz,
          errCode,
          errMessage
        });

        // TODO: Use `errCode` to display a custom error message to the user.
      }

      /**
     * Handles the result of the generation algorithm.
     * This result excludes subsequent user edits in the editor.
     */
      function handleTaskSuccess(message) {
        const { biz, data } = message;
        const results = Array.isArray(data) ? data : [];

        console.log("Generation task completed:", {
          biz,
          results
        });

        // TODO: Process the algorithm's generation result according to your business requirements.
      }

      /**
     * Handles the final result returned when the user clicks "Save" or "Download".
     */
      function handleSubmitAll(message) {
        const results = Array.isArray(message.data) ? message.data : [];

        console.log("Received final result from editor:", results);

        // TODO: Save the schema as is. Do not modify its content.
        // TODO: Re-host the result images promptly. The returned image URLs are valid for 7 days by default.
      }

      /**
     * Listens for messages sent from the editor iframe.
     */
      window.addEventListener("message", function (event) {
        // Accept messages only from the current editor iframe.
        if (event.source !== editorIframe.contentWindow) {
          return;
        }

        // Verify the message origin to avoid processing messages from other websites.
        if (event.origin !== editorOrigin) {
          console.warn("Ignoring message from unknown origin:", event.origin);
          return;
        }

        const message = event.data;

        if (!message || typeof message !== "object") {
          return;
        }

        switch (message.action) {
          case "pageReady":
            console.log("Editor page is ready");

            // Send initialization parameters after receiving 'pageReady'.
            editorIframe.contentWindow.postMessage(
              {
                action: "init",
                data: editorInitData
              },
              editorOrigin
            );
            break;

          case "generate":
            // Production interception is an asynchronous process. The result is sent back to the editor via a 'respond' message.
            void handleGenerate(message);
            break;

          case "error":
            handleEditorError(message);
            break;

          case "taskSuccess":
            handleTaskSuccess(message);
            break;

          case "submitAll":
            handleSubmitAll(message);
            break;

          default:
            console.warn("Received an unrecognized message from the editor:", message);
        }
      });

      /**
     * Gets the editor URL from your server and sets the iframe src.
     */
      async function loadEditor() {
        try {
          const response = await fetch("/api/aidge-editor/access-url", {
            method: "POST",
            cache: "no-store"
          });

          if (!response.ok) {
            throw new Error(`Failed to get the editor URL: HTTP ${response.status}`);
          }

          const result = await response.json();

          if (!result.src) {
            throw new Error("Server did not return an editor src");
          }

          const editorUrl = new URL(result.src);

          if (editorUrl.protocol !== "https:") {
            throw new Error("The editor URL must use HTTPS");
          }

          // Load the iframe after the message listener is registered to avoid missing the 'pageReady' message.
          // Use the one-time key immediately after it is generated.
          editorIframe.src = editorUrl.href;
        } catch (error) {
          console.error("Failed to load the editor:", error);
        }
      }

      loadEditor();
    </script>
  </body>
</html>

3.3.8. Biz business identifier mapping

The biz business identifier indicates the capability or tier of a message. The client must route messages from the editor based on the biz value; when returning respond / applyToolResult, the client must include the original biz value.

Capability / tier

Tool input value

Message biz

Submitted ApiType

Image Translation Standard Edition

translate

translate

ImageTranslationStandard

Image Translation Pro Edition

translatePro

translatePro

ImageTranslationPro

Image Translation dual-tier

translateBoth

Use translate or translatePro depending on the current tier.

ImageTranslationStandard or ImageTranslationPro

Smart Erase Standard Edition

erase

ImageRemove

ImageRemove

Smart Erase Pro Edition

erasePro

ImageRemovalPro

ImageRemovalPro

Smart Erase dual-tier

eraseBoth

Use ImageRemove or ImageRemovalPro depending on the current tier.

ImageRemove or ImageRemovalPro

Image Matting

matting

ImageMatting

ImageMatting

Text Translation (Right panel)

— (Available with any capability)

textTranslation

— (Only applies when chargeTextTranslation=true)

Key points: For Image Translation, biz is the tier name (translate / translatePro), not the ApiType. The biz values in this table apply to all messages the capability sends to the host (generate / respond / applyToolResult / taskSuccess / submitAll / error).

4. Custom features

4.1 Generation interception

The charge interception feature takes effect only when charge in the editor initialization configuration is set to true.

The generation interception feature lets an integrator control users' paid API call requests. Based on the integrator's response, the editor decides whether to proceed with the call, which allows for a final confirmation before execution.

Use case: When a user makes a paid API call in the editor, the integrator can verify if the user's available balance or permissions are sufficient.

Procedure:

  1. Listen for messages from the editor and implement the integrator's business logic.

let receiveBiz = "";

window.addEventListener("message", (ev: MessageEvent) => {
  const { data, action, biz } = ev.data ?? {};
  if (action === "generate") {
    // Save the business type. It must be sent back unchanged when replying to the editor.
    receiveBiz = biz;

    // The number of images the user is about to generate.
    const { imageNum } = data ?? {};

    console.log("Generation request:", {
      biz,
      imageNum,
      data,
    });

    // TODO: Check the user's balance, permissions, etc., here.
  }
});
  1. The return message controls whether the execution flow continues. When the success field in the message is true, the tool execution continues. When it is false, the tool execution is interrupted and a prompt is displayed to the user.

// true: Continues the generation and incurs charges.
// false: Aborts the generation process.

const success = true;

iframeEle.contentWindow?.postMessage(
  {
    biz: receiveBiz,
    action: "respond",
    success,
  },
  editorOrigin,
);
The value of the biz parameter depends on the capability (such as the tier name for Image Translation, the ApiType for Erase and Matting, or Text Translation textTranslation, see §3.3.8). You must return this value as is.

4.2 Re-editing

The secondary editing feature takes effect only when the reEdit setting in the editor initialization configuration is set to true.

The secondary editing feature allows you to load historical result data into the editor and continue editing. To enable this feature, the client must pass the historical result data in the reEditData parameter of the initialization configuration. This data can be obtained from the genFiles field in an API response (for details, see Section 6) or from the result data returned by the editor (for details, see Sections 5.2 and 5.3).

  • reEditData is a string, which is deserialized into an EditorData[] array (see §5.3 for the structure). You can obtain the data from genFiles (§6) returned by the API or the result data (§5.2 / §5.3) returned by the editor.

  • Multiple images are supported: Each element in the array corresponds to one image, and the editor will rebuild them as multiple tasks. For a single image, pass an array of length 1.

  • The tool value must match the capability used to generate the result (for example, for a matting result, pass tool: "matting"). Otherwise, the UI capability will not match the data.

  • Do not modify the result data during storage or transmission, as this may prevent it from loading correctly.

Example of secondary editing for image translation (Replace the placeholders, such as fileUrl, srcImage, and repairedUrl, with the actual result URLs):

iframeEle.contentWindow?.postMessage(
  {
    action: "init",
    data: {
      tool: "translate",
      reEdit: true,
      reEditData: JSON.stringify([
        {
          editInfo: {
            goodsRects: { top: 0, left: 0, width: 802, height: 802, degree: 0 },
            languages: ["en"],
            textAreas: [
              {
                verticalLayout: "top",
                horizontalLayout: "center",
                color: "#f6eec1",
                fontsize: 50,
                lineCount: 1,
                content: "Hello Kitty Sleep Companion Night Light",
                texts: [
                  {
                    valid: true,
                    verticalLayout: "top",
                    horizontalLayout: "center",
                    color: "#f6eec1",
                    imageRect: { top: 27, left: 68, width: 692, height: 100, degree: 0 },
                    textRect: { top: 27, left: 68, width: 692, height: 100, degree: 0 },
                    fontsize: 50,
                    language: "en",
                    value: "Hello Kitty Sleep Companion Night Light",
                    lineCount: 1
                  }
                ]
              }
            ],
            resultImageIds: ["xxx"],
            repairedUrl: "xxx",
            font: ["AlibabaSans-Regular"]
          },
          srcImage: "xxx",
          resultList: [{ language: "en", fileUrl: "xxx" }]
        }
      ])
    }
  },
  editorOrigin
);

Smart Matting/Smart Erase re-editing example (no text, textAreas is empty, repairedUrl is the result image or background-removed image, and srcImage is the original image):

iframeEle.contentWindow?.postMessage(
  {
    action: "init",
    data: {
      tool: "matting", // For erase, pass erase, erasePro, or eraseBoth
      reEdit: true,
      reEditData: JSON.stringify([
        {
          editInfo: {

            languages: [],


            textAreas: [],


            resultImageIds: [],

            repairedUrl: "xxx", // Result image after matting or erasing

            font: [ ]

          },
          srcImage: "xxx",       // Source image
          resultList: [{ language: "", fileUrl: "xxx" }]
        }
      ])
    }
  },
  editorOrigin
);

4.3 API calls via the integrator

This is effective only when enableToolExecution=false. When a user triggers a capability, the editor does not call the API directly. Instead, it sends the batch call information to the host in a single generate request. After the host completes the batch call, it returns the batch results through a single applyToolResult call, and the editor renders the results as a task list. The Image Translation, Smart Erase, and Smart Matting capabilities all use this process. A single image is treated as a batch with a length of 1.

window.addEventListener("message", async (event) => {
  const { action, biz, data } = event.data ?? {};
  if (action === "generate") {
    try {
      // data = { imageNum, apiType, items: [{ name, params, detail }] }
      // Route to the corresponding capability based on 'biz' and iterate through 'items' for the batch call (invokeToolApi is an example).
      const results = await Promise.all(
        data.items.map((item) => invokeToolApi({ biz, params: item.params })),
      );
      // Return an array with a length equal to data.imageNum, in the same order as 'items'. The structure of each item is the same as a single element in reEditData.
      // (For image translation, you can use genFiles from the backend directly; for erase/matting, see the structure below).
      const resultData = results.map((r) => r.genFilesItem);
      iframeEle.contentWindow.postMessage(
        { biz, action: "applyToolResult", data: resultData }, editorOrigin);
    } catch (error) {
      console.error("Capability API call failed:", error);
      // Batch call failure: Pass an empty string for 'data'. The integrator is responsible for displaying a toast notification.
      iframeEle.contentWindow.postMessage(
        { biz, action: "applyToolResult", data: "" }, editorOrigin);
    }
  }
});

Minimum structure of each GenFilesItem for removal/matting (no text, and the textAreas parameter is an empty array):

{
  editInfo: {
    repairedUrl: "https://.../result.png", // Result image after erasing or matting.

    textAreas: [],


    resultImageIds: [],


    languages: [],


    font: [],

  },
  srcImage: "https://.../origin.png",       // Source image.
  resultList: [{ language: "", fileUrl: "https://.../result.png" }],
}
  • biz must be consistent with generate.biz (see §3.3.8). data is an array of the GenFilesItem[] type. The length of the array is equal to generate.data.imageNum, and the elements correspond to the items in order. The structure of each element is consistent with a single element of reEditData. If the entire batch call fails, pass "".

  • If the number of returned items is less than the number submitted, the editor treats the corresponding tasks as failed. If the data is not an array or cannot be parsed, the editor treats the entire batch as failed.

  • Smart Matting: The dimensions of the result image may differ from the original image. We recommend that you include tps-{width}-{height} in the URL of the result image or allow the editor domain to read image pixels across domains. Otherwise, the canvas may fall back to its default size and cause rendering misalignment.

5. Retrieve results

5.1. Retrieving generation task results

After a successful generation task, the integrator retrieves the result data by listening for a message where the action is taskSuccess.

This is the raw result from the algorithm, not the final result. It excludes any subsequent edits made by the user in the editor.
interface ResultItem {
  id: string;
  url: string;
}

type Result = ResultItem[];

window.addEventListener("message", (ev: MessageEvent) => {
  const { data, action, biz } = ev.data ?? {};

  if (action === "taskSuccess") {
    const result: Result = data;

    console.log("Business:", biz, "generation task completed. Result:", result);
  }
});

5.2. Retrieving the final result

Method 1: Event listening

When a user performs the following actions, the editor sends the result data to the integrator:

  1. Clicks the 'Save' button: Returns the result image and data payload for the current canvas.

  2. Clicks the 'Download' button: Downloads the result image to the local device and returns the result image and data payload.

window.addEventListener("message", (ev: MessageEvent) => {
  const { data, action } = ev.data ?? {};

  if (action === "submitAll") {
    // TODO: Handle the final task result here
    console.log("Received task result:", data);
  }
});

Method 2: Proactive retrieval

The integrator can proactively retrieve result data from the editor by sending a message with the action set to requestResult.

iframe.contentWindow?.postMessage(
  {
    action: "requestResult",
  },
  editorOrigin,
);

After the editor receives this message, it returns the complete result data as shown below.

window.addEventListener("message", (ev: MessageEvent) => {
  const { data, action } = ev.data ?? {};
 

  if (action === "submitAll") {
    // TODO: Handle the final task result here
    console.log("Received task result:", data);
  }
});

5.3. Data format

The returned data includes the url of the result image for the current canvas and the editData payload.

The integrator must save the result data. If the re-editing feature is enabled, this data can be passed to the editor to resume editing.

Do not modify the result data during storage or transmission. Any changes can prevent the editor from correctly loading historical data. The default validity period for the result image's signed URL is 7 days. The integrator should back up the image promptly to avoid access issues when the link expires.
interface ResultType {
  /**
   * Indicates whether this submission was triggered by the user clicking "Download Image".
   * The message body for download and save operations is identical. The integrator can use this flag to prevent duplicate counting or redundant notifications.
   */
  isDownload: boolean;

  /** The result ID, used to track both the algorithm's result and the user-adjusted result. */
  id: string;

  /** Original image URL (a single, directly accessible signed URL). */
  originalUrl: string;

  /** Result image URL (a single, directly accessible signed URL). */
  url: string;

  /**
   * Complete editor data, as a JSON string.
   * Matches the initialization parameter `reEditData`. After deserialization, it becomes an array of objects that conform to the EditorData structure.
   */
  editData: string;
}

interface EditorData {
  /** Complete editor data: text areas, user-added layers, repaired base image, fonts, etc. */
  editInfo: EditInfo;
  /** Original image URL. */
  srcImage: string;
  /** The list of result images, organized by language (an algorithmic structure). This is always a single-element array for single-language translation. */
  resultList: ResultImageItem[];
}

interface EditInfo {
  /** Product area. */
  goodsRects?: Rect;
  /** List of target languages. */
  languages: string[];
  /** List of text areas (algorithm-recognized "source → translation" areas). */
  textAreas: TextArea[];
  /** List of result image IDs. */
  resultImageIds: string[];
  /** URL of the repaired base image with text removed. */
  repairedUrl: string;
  /** List of fonts. */
  font: string[];
  /** Specific to Image Translation Standard Edition: The URL of the uploaded original image (the Pro edition uses `srcImage`). */
  pictUrl?: string;
  /**
   * Layers added by the user in the editor, such as stickers, assets, or text.
   * This is stored separately because `textAreas` only models the text areas identified by the algorithm and cannot represent these additional layers.
   * This field is not included in the original response from the algorithm and is only present if the user has added new layers.
   */
  editorLayers?: EditorLayer[];
}

interface Rect {
  top: number;
  left: number;
  width: number;
  height: number;
  /** Rotation angle. */
  degree: number;
}

interface TextArea {
  /** Vertical alignment: `top`, `center`, or `bottom`. */
  verticalLayout: string;
  /** Horizontal alignment: `left`, `center`, or `right`. */
  horizontalLayout: string;
  /** List of translated texts (by language). */
  texts: TextItem[];
  color: string;
  fontsize: number;
  lineCount: number;
  /** Source text content. */
  content: string;
}

interface TextItem {
  valid: boolean;
  verticalLayout: string;
  horizontalLayout: string;
  color: string;
  /** Position on the image. */
  imageRect: Rect;
  fontsize: number;
  /** Language. */
  language: string;
  /** Text box position. */
  textRect: Rect;
  /** Translated text content. */
  value: string;
  lineCount: number;

  /** Stroke color. */
  stroke?: string;
  /** Stroke width. */
  strokeWidth?: number;
  /** Paint order: `stroke` or `fill`. */
  paintFirst?: string;
  /** Shadow. */
  shadow?: Shadow;
  /** Character spacing. */
  charSpacing?: number;
  /** Text background color. */
  backgroundColor?: string;
  /** Line height. */
  lineHeight?: number;
  /** Text decoration: `underline` or `line-through`. */
  textDecoration?: string;
}

interface Shadow {
  color: string;
  offsetX: number;
  offsetY: number;
  /** Blur radius. */
  blur: number;
}

interface ResultImageItem {
  /** Language. */
  language: string;
  /** Result image URL. */
  fileUrl: string;
}

6. API layer information

The image translation Standard and Pro editions return an almost identical layer structure. In both, the source image URL is located in the SrcImage field. The Standard edition also includes the EditInfo.PictUrl field, which stores the URL of the uploaded source image. In the raw API response, the Data.GenFiles field is a String that, when deserialized, becomes an Array[Object] you can pass directly to the editor as reEditData for re-editing (see §4.2).

For smart erase and smart matting, the genFiles structure is identical. The only difference is that the TextAreas array is empty for unedited images. RepairedUrl is the URL of the resulting base image after erasing or matting. You can also use this data as reEditData.
The [*] notation represents any element in an array. For example, GenFiles[*] refers to any layer information item.

No.

Parameter

Type

Description

1

Data.GenFiles

String

Contains the editor's protocol information. This field is returned only when UseImageEditor = true. The value is a string that deserializes into an Array[Object].

2

Data.GenFiles[*].SrcImage

String

The URL of the source image.

3

Data.GenFiles[*].EditInfo

Object

Contains detailed editor information.

4

Data.GenFiles[*].EditInfo.PictUrl

String

The URL of the uploaded source image. This field is returned only by the image translation Standard edition.

5

Data.GenFiles[*].EditInfo.ResultImageIds

Array[String]

An array of global IDs for the translated images.

6

Data.GenFiles[*].EditInfo.RepairedUrl

String

The URL of the image resulting from an erase or matting operation.

7

Data.GenFiles[*].EditInfo.Languages

Array[String]

A list of translation languages.

8

Data.GenFiles[*].EditInfo.TextAreas

Array[Object]

A list of text box objects.

9

Data.GenFiles[*].EditInfo.TextAreas[*].Fontsize

Number

The font size.

10

Data.GenFiles[*].EditInfo.TextAreas[*].Content

String

The original text before translation.

11

Data.GenFiles[*].EditInfo.TextAreas[*].Color

String

The text color, for example, "#ffffff".

12

Data.GenFiles[*].EditInfo.TextAreas[*].VerticalLayout

String

The vertical alignment. Valid values are "center", "top", and "bottom".

13

Data.GenFiles[*].EditInfo.TextAreas[*].HorizontalLayout

String

The horizontal alignment. Valid values are "center", "left", and "right".

14

Data.GenFiles[*].EditInfo.TextAreas[*].LineCount

Number

The number of lines in the text box.

15

Data.GenFiles[*].EditInfo.TextAreas[*].Texts

Array[Object]

A list of translated text objects.

16

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].Fontsize

Number

The font size.

17

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].Language

String

The translation language.

18

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].Valid

Boolean

Whether TextItem is valid

19

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].ImageRect

Object

The area for image inpainting.

20

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].TextRect

Object

The bounding box of the translated text.

21

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].Color

String

The text color.

22

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].Value

String

The translated text.

23

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].VerticalLayout

String

The vertical alignment.

24

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].HorizontalLayout

String

The horizontal alignment.

25

Data.GenFiles[*].EditInfo.TextAreas[*].Texts[*].LineCount

Number

The number of lines of the translated text.

26

Data.GenFiles[*].EditInfo.GoodsRects

Object

The item box region.

27

Data.GenFiles[*].EditInfo.Font

Array[String]

A list of font types.

28

Data.GenFiles[*].ResultList

Array[Object]

A list of translation results.

29

Data.GenFiles[*].ResultList[*].Language

String

The translation language.

30

Data.GenFiles[*].ResultList[*].FileUrl

String

The URL of the translated image.

7. Supported language pairs

For the language pairs supported by Image Translation Standard Edition and Image Translation Pro Edition, see the language mapping.

8. Error codes

See error codes for details.

9. Pricing

Billable item

Billing unit

Price (CNY)

text translation

per million characters

¥50

Image Translation Standard Edition

per image

¥0.015

Image Translation Pro Edition

per image

¥0.06

Smart Erasing Standard Edition

per image

¥0.025

Smart Erasing Pro Edition

per image

¥0.12

Smart Matting

per image

¥0.002