Image translation editor protocol
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 |
|
|
|
Image Translation Pro Edition | |||
Smart Erasing Standard Edition | Supports targeted erasing through various methods:
|
| |
Smart Erasing Pro Edition |
| ||
Smart Matting |
|
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 |
|
|
Left console |
|
|
Pinned top bar | Common features
|
|
Right-side editing panel | image translation |
|
smart erase Standard smart erase Pro AI cutout | None | |
Center canvas |
|
|
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:
|
|
Left configuration panel | Main upload area | Common features applicable to all five capabilities
| Single-image upload area⬇️
Multi-image upload area⬇️
|
Left configuration panel | Upload progress |
|
|
Left configuration panel | image translation - Version |
|
|
Left configuration panel | image translation - Standard |
|
|
Left configuration panel | image translation - Pro |
|
|
Left configuration panel | image translation - Translate button |
|
|
Left configuration panel | smart erase - Version |
|
|
Left configuration panel | smart erase - Standard | Standard version Element Erase, Area Erase, and Text Erase are mutually exclusive options.
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.
|
|
smart erase - Pro |
|
| |
smart erase - Erase button |
|
| |
Left configuration panel | AI cutout |
|
Click the background color swatch to open the color picker.
|
Start Cutout
|
| ||
Processing state | Task list | Common features applicable to all five capabilities
UI Style
| Full UI⬇️
Failed state⬇️
|
Processing state | Full UI | image translation Standard |
|
Processing state | Full UI | image translation Pro |
|
Processing state | Full UI | smart erase Standard |
|
Processing state | Full UI | smart erase Pro |
|
Processing state | Full UI | AI cutout |
|
Completed state | Save | Common feature applicable to translation, cutout, and erase functions. |
|
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. |
| |
Task history | Tasks | Click the "Task history" button to view successfully processed tasks.
| Click "Task history" in the top bar⬇️
In task history, you can filter the results⬇️
|
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.
| Add Text - Input custom text⬇️
Add Sticker - Use the platform's sticker library⬇️
Add Asset - Upload an asset from your local device⬇️
|
Specific editing capabilities | Applies only to image translation (Standard and Pro).
|
|
3. Access method
3.1 Overall workflow
The client sends a request to the server, for example,
POST /api/aidge-editor/access-url.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.
The server returns the complete iframe URL to the client.
The client creates or refreshes an iframe and sets its
srcattribute to the received URL.The Alibaba Cloud authentication service validates the key. Upon successful validation, the editor page loads.
Once the editor page loads, it sends a load completion event to the parent page using
postMessage.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

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.



3.2.4 Attach a permission policy
Search for "Aidge" and select the corresponding permission policy.

3.2.5 Obtain Role ARN, AccessKey ID, and AccessKey Secret



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 |
|
| 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.
The array must contain one value from each capability group. For example: |
2 | image URL |
|
| No | - | The URL of the image that you want to translate. In batch mode ( |
3 | upload mode |
|
| No |
|
|
4 | batch limit |
|
| No |
| This parameter takes effect only when |
5 | source language |
|
| 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 |
|
| 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 |
|
| No |
| The UI language of the editor. Options: |
8 | Default state for "preserve original text" (brand/product names) |
|
| No |
|
|
9 | re-editing |
|
| No |
|
|
10 | re-editing data |
|
| No |
| The result data of a processed image, which includes layer information. You can get this data from an API response. |
11 | charge interception |
|
| No |
|
|
12 | charge interception (text translation) |
|
| No |
| Production interception for Text Translation on the right-side panel is independent of |
13 | tool execution |
|
| No |
|
|
14 | editor UI configuration |
|
| 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 |
|
|
|
|
2 | Sidebar title |
|
|
| Title at the top of the sidebar. |
3 | History button visibility |
|
|
| When |
4 | History button text |
|
|
| - |
5 | History panel title |
|
|
| - |
6 | Upload button text |
|
|
| - |
7 | Add text button visibility |
|
|
|
|
8 | Add sticker button visibility |
|
|
|
|
9 | Add asset button visibility |
|
|
|
|
Image translation (Standard and Pro)
No. | Name | Parameter | Type | Default | Description |
10 | 'Image translation' panel title |
|
|
| - |
11 | 'Standard' label text |
|
|
| When |
12 | 'Pro' label text |
|
|
| When |
13 | 'Standard' tooltip text |
|
|
| Set to |
14 | 'Pro' tooltip text |
|
|
| Set to |
15 | 'Language' section title |
|
|
| - |
16 | 'Source language' label text |
|
|
| - |
17 | 'Source language' tooltip text |
|
|
| Set to |
18 | 'Target language' label text |
|
|
| - |
19 | 'Target language' tooltip text |
|
|
| Set to |
20 | 'Brand name protection' label text |
|
|
| - |
21 | 'Brand name protection' tooltip text |
|
|
| Set to |
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 |
|
|
| - |
24 | 'Translate text' switch label |
|
|
| 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 |
|
|
| - |
26 | "Standard" label text |
|
|
| Set to |
27 | "Pro" label text |
|
|
| Set to |
28 | "Standard" tooltip text |
|
|
| Set to |
29 | "Pro" tooltip text |
|
|
| Set to |
30 | Main object erase entry |
|
|
| Shows or hides the entry for erasing the main object. This feature is available only in the Standard version.
|
31 | Non-main object erase entry |
|
|
| Shows or hides the entry for erasing non-main objects. This feature is available only in the Standard version.
|
32 | Area erase entry |
|
|
| Shows or hides the entry for area erase (box or lasso select). This feature is available only in the Standard version.
|
33 | Text erase entry |
|
|
| Shows or hides the entry for erasing specified text. This feature is available only in the Standard version.
|
34 | Erase button text |
|
|
| - |
Intelligent matting
No. | Name | Parameter | Type | Default | Description |
35 | Intelligent matting panel title |
|
|
| - |
36 | 'Background type' label |
|
|
| - |
37 | 'Solid color' option label |
|
|
| - |
38 | 'Transparent' option label |
|
|
| - |
39 | Default background |
|
|
| Enum value: |
40 | 'Output size' group title |
|
|
| - |
41 | Label for the 'target width' field |
|
|
| - |
42 | Label for the 'target height' field |
|
|
| - |
43 | Text on the intelligent matting button |
|
|
| - |
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 |
|
| No | This is the business identifier. The value is |
|
| Yes | The message type. |
|
| 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 |
|
| Yes | The business identifier associated with the error. |
|
| Yes | The message type, which is always |
|
| Yes | A unique code that identifies the error. For example, |
|
| 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
| Trigger | Message body | Key data | Related message |
| The editor page has loaded. |
| No other fields. | The client frontend responds with an |
| The user clicks the back button when |
| No other fields. | - |
| The user initiates a paid API call when |
|
| The client frontend must respond with a |
| An editor operation fails. |
|
For more information, see section 3.3.4. | - |
| A generation task completes successfully. |
|
For more information, see section 5.1. | - |
| The user clicks Save or Download, or the editor responds to a |
|
For more information, see section 5.3. | Triggered by a |
3.3.6 Messages the editor can receive
Communication direction: client frontend → editor iframe
| Trigger | Message body | Key data | Editor action |
| After the client frontend receives |
|
For more information, see section 3.3.1. | Initializes the editor based on the configuration. |
| When the UI language needs to be switched at runtime. |
|
| Switches the UI language dynamically without reloading the page. |
| After the client frontend receives |
|
For more information, see section 4.1. | Determining whether to execute a paid API call based on |
| After the client frontend completes the API call. |
|
For more information, see section 4.3. | Loads and displays the result. |
| When the client frontend needs to retrieve the complete current result. |
| No other fields. For more information, see section 5.1. | Returns the complete result in a |
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 | Submitted ApiType |
Image Translation Standard Edition |
|
|
|
Image Translation Pro Edition |
|
|
|
Image Translation dual-tier |
| Use | ImageTranslationStandard or ImageTranslationPro |
Smart Erase Standard Edition |
|
|
|
Smart Erase Pro Edition |
|
|
|
Smart Erase dual-tier |
| Use | ImageRemove or ImageRemovalPro |
Image Matting |
|
|
|
Text Translation (Right panel) | — (Available with any capability) |
| — (Only applies when |
Key points: For Image Translation,bizis the tier name (translate/translatePro), not the ApiType. Thebizvalues 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:
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.
}
});The return message controls whether the execution flow continues. When the
successfield in the message istrue, the tool execution continues. When it isfalse, 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 thebizparameter depends on the capability (such as the tier name for Image Translation, the ApiType for Erase and Matting, or Text TranslationtextTranslation, 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).
reEditDatais astring, which is deserialized into anEditorData[]array (see §5.3 for the structure). You can obtain the data fromgenFiles(§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
toolvalue must match the capability used to generate the result (for example, for a matting result, passtool: "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" }],
}
bizmust be consistent withgenerate.biz(see §3.3.8).datais an array of theGenFilesItem[]type. The length of the array is equal togenerate.data.imageNum, and the elements correspond to theitemsin order. The structure of each element is consistent with a single element ofreEditData. 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:
Clicks the 'Save' button: Returns the result image and data payload for the current canvas.
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, thegenFilesstructure is identical. The only difference is that theTextAreasarray is empty for unedited images.RepairedUrlis the URL of the resulting base image after erasing or matting. You can also use this data asreEditData.
The[*]notation represents any element in an array. For example,GenFiles[*]refers to any layer information item.
No. | Parameter | Type | Description |
1 |
|
| Contains the editor's protocol information. This field is returned only when |
2 |
|
| The URL of the source image. |
3 |
|
| Contains detailed editor information. |
4 |
|
| The URL of the uploaded source image. This field is returned only by the image translation Standard edition. |
5 |
|
| An array of global IDs for the translated images. |
6 |
|
| The URL of the image resulting from an erase or matting operation. |
7 |
|
| A list of translation languages. |
8 |
|
| A list of text box objects. |
9 |
|
| The font size. |
10 |
|
| The original text before translation. |
11 |
|
| The text color, for example, |
12 |
|
| The vertical alignment. Valid values are |
13 |
|
| The horizontal alignment. Valid values are |
14 |
|
| The number of lines in the text box. |
15 |
|
| A list of translated text objects. |
16 |
|
| The font size. |
17 |
|
| The translation language. |
18 |
|
| Whether |
19 |
|
| The area for image inpainting. |
20 |
|
| The bounding box of the translated text. |
21 |
|
| The text color. |
22 |
|
| The translated text. |
23 |
|
| The vertical alignment. |
24 |
|
| The horizontal alignment. |
25 |
|
| The number of lines of the translated text. |
26 |
|
| The item box region. |
27 |
|
| A list of font types. |
28 |
|
| A list of translation results. |
29 |
|
| The translation language. |
30 |
|
| 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 |













































