Wanx text-to-image V1 API reference

更新时间:
复制 MD 格式

This topic describes the input and output parameters for the Wanx text-to-image V1 model.

Related guide: Text-to-image

Important
  • This document applies only to the China (Beijing) region. You must use an API key from this region.

  • We recommend using the fully upgraded text-to-image V2 model.

Model overview

Model overview

Model

Introduction

wanx-v1

The Wan text-to-image generation model. Its main features include the following:

  • Supports input in both Chinese and English.

  • Supports a variety of image styles.

  • Supports content or style transfer based on reference images to create a wider range of styles, subjects, and genres.

Model description

Model

Unit price

Rate limit (shared by Alibaba Cloud account and RAM users)

Free quota

Request per second (RPS) for task submission

Number of concurrent tasks

wanx-v1

CNY 0.16 per image

2

1

Free quota: 500 images

Valid for 180 days after activation

For more information, see Model billing and rate limiting.

Prerequisites

You can call the text-to-image V1 model API over HTTP or using the DashScope SDK.

Before making a call, get an API key and export the API key as an environment variable.

To call the API using the SDK, install the DashScope SDK. The SDK is available for Python and Java.

HTTP invocation

Image models take a long time to process. To prevent timeouts, HTTP calls support only asynchronous result retrieval. Two requests are required:

  1. Create a task to get a task ID: Send a request to create a task. The response returns a task ID (task_id).

  2. Query the result using the task ID: Use the task ID from the previous step to query the task status and result. If the task is successful, the response returns an image URL that is valid for 24 hours.

Note

After creation, the task enters a queue for scheduling. Call the query API to retrieve the task status and result.

Step 1: Create a task to get a task ID

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Request parameters

Text-to-image

Positive prompt

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges."
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1
    }
}'
    

Positive + negative prompt

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges.",
        "negative_prompt": "Do not use red elements"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1
    }
}'
    

Generation from a reference image

Based on reference image content

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "A heroic woman with black hair, with golden butterflies flying around, and a faint ink wash bamboo forest in the background, high detail, high quality.",
        "ref_image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1,
        "ref_strength": 1.0,
        "ref_mode": "repaint"
    }
}'
    

Based on reference image style

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "There is a small black cat",
        "ref_image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/gpqnqy/house.png"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1,
        "ref_strength": 0.7,
        "ref_mode": "refonly"
    }
}' 
Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be enable.

Important

If this request header is missing, the error "current user api does not support synchronous calls" is returned.

X-DashScope-WorkSpace string (Optional)

The ID of the Model Studio workspace. Example: llm-xxxx.

You can get the Workspace ID.

Details

Set this parameter to your Model Studio API key.

  • If you use an Alibaba Cloud account API key, this parameter is optional. Without it, Alibaba Cloud account permissions apply. With it, workspace permissions apply.

  • If you use a RAM user API key, this parameter is required because RAM users must belong to a workspace.

The workspace must have model access permission. If not granted, see Authorize a sub-workspace to call models.

For details about Alibaba Cloud accounts and RAM users, see Alibaba Cloud account management.

Request body

model string (Required)

The model name. Example: `wanx-v1`.

input object (Required)

The basic input information, such as the prompt.

Properties

prompt string (Required)

The positive prompt. This describes the elements and visual features that you want in the generated image.

This parameter supports both Chinese and English. The maximum length is 800 characters. Each Chinese character or letter is counted as one character. Any excess characters are automatically truncated.

Example: A sitting orange cat, happy and cute, realistic and accurate.

For tips on using prompts, see Text-to-image prompt guide.

negative_prompt string (Optional)

The negative prompt. This describes the content that you do not want to see in the image and can be used to constrain the output.

This parameter supports both Chinese and English. The maximum length is 500 characters. Any excess characters are automatically truncated.

Example: low resolution, error, worst quality, low quality, deformed, extra fingers, bad proportions.

ref_img string (Optional)

The URL of the reference image. The model generates an image with a similar style based on this image.

Image requirements:

  • Image format: Common formats are supported, such as JPG, JPEG, PNG, BMP, TIFF, and WEBP.

  • Image size: No more than 10 MB.

  • Image resolution: At least 256 × 256 pixels and no more than 4096 × 4096 pixels.

  • The URL cannot contain Chinese characters.

parameters object (Optional)

The image editing parameters.

Properties

style string (Optional)

The style of the output image. The following styles are supported:

Enumeration values

  • <auto>: Default value. The model randomly selects an image style.

  • <photography>: Photography.

  • <portrait>: Portrait.

  • <3d cartoon>: 3D cartoon.

  • <anime>: Animation.

  • <oil painting>: Oil painting.

  • <watercolor>: Watercolor.

  • <sketch>: Sketch.

  • <chinese painting>: Chinese painting.

  • <flat illustration>: Flat illustration.

size string (Optional)

The resolution of the output image. The following resolutions are supported:

Enumeration values

  • 1024×1024: Default value.

  • 720×1280

  • 768×1152

  • 1280×720

n integer (Optional)

The number of images to generate. The value must be an integer from 1 to 4. The default value is 4.

seed integer (Optional)

The random number seed, which is used to control the randomness of the generated content. The value must be in the range of [0, 2147483647].

If you do not provide a seed, the algorithm automatically generates a random number to use. If you provide a seed, the algorithm generates seeds for n images based on the value of `n`. For example, if n=4, the algorithm generates images with the seeds `seed`, `seed+1`, `seed+2`, and `seed+3`.

To ensure the generated content is relatively stable, use the same seed value for each request.

ref_strength float (Optional)

Controls the similarity between the output image and the reference image.

The value must be in the range of [0.0, 1.0]. A larger value indicates that the generated image is more similar to the reference image.

ref_mode string (Optional)

The mode for generating an image based on a reference image. The following modes are supported:

Enumeration values

  • repaint: Default value. Generates an image based on the content of the reference image.

  • refonly: Generates an image based on the style of the reference image.

Response parameters

Successful response

Save the task_id to query the task status and result.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See Error codes.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

The task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: The task does not exist or its status is unknown.

request_id string

Unique request identifier for tracing and troubleshooting.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

Step 2: Query the result by task ID

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Request parameters

Query task results

Replace 86ecf553-d340-4e21-xxxxxxxxx with your actual task_id.

If you use a model in the Singapore region, replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where WorkspaceId is your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The ID of the task.

Response parameters

Success response

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "request_id": "85eaba38-0185-99d7-8d16-4d9135238846",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/b2.png"
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 2,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 2
    }
}

Failure response

When a task fails, task_status is FAILED with an error code and message. See Error codes.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match the allowed size ['1024*1024', '720*1280', '1280*720']",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

Partial failure response

The model can generate multiple images per task. If at least one succeeds, the task status is SUCCEEDED and URLs of successful images are returned. Failed images include a failure reason. Usage statistics count only successful results. See Error codes.

{
    "request_id": "85eaba38-0185-99d7-8d16-4d9135238846",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occured during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

output object

The task output.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: The task does not exist or its status is unknown.

task_metrics object

Statistics for the task result.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

results array of object

The list of task results, including image URLs, error messages in case of partial task failure.

Structure

{
    "results": [
        {
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

usage object

The output statistics. Only successful results are counted.

Properties

image_count integer

Number of images successfully generated. Billing: Cost = Number of images × Unit price.

request_id string

Unique request identifier for tracing and troubleshooting.

DashScope SDK invocation

Make sure you have installed the latest version of the DashScope SDK. Otherwise, a runtime error may occur. For more information, see Install the SDK.

The DashScope SDK currently supports Python and Java.

The parameter names in the SDK are mostly consistent with those in the HTTP API. The parameter structure varies based on the SDK encapsulation for each language. For parameter descriptions, see HTTP invocation.

Because image model processing can be time-consuming, the underlying service is provided asynchronously. The SDK is encapsulated to support both synchronous and asynchronous invocation methods.

Python SDK invocation

Synchronous call

Request example

Text-to-image

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
from dashscope import ImageSynthesis
import os

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges."


print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=os.getenv("DASHSCOPE_API_KEY"),
                          model=ImageSynthesis.Models.wanx_v1,
                          prompt=prompt,
                          n=1,
                          style='<watercolor>',
                          size='1024*1024')
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
    # Save the image in the current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

Generation from a reference image

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
from dashscope import ImageSynthesis
import os

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges."

# Method to upload the reference image: choose either a URL or a local path
# If both are provided, the ref_img parameter has higher priority
# Use a public URL
ref_img = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
# Use a local file path
sketch_image_url = './girl.png'

print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=os.getenv("DASHSCOPE_API_KEY"),
                          model=ImageSynthesis.Models.wanx_v1,
                          prompt=prompt,
                          n=1,
                          style='<auto>',
                          size='1024*1024',
                          ref_mode='repaint',
                          ref_strength=1.0,
                          # sketch_image_url=sketch_image_url,
                          ref_img=ref_img)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
    print(rsp.output)
    # Save the image to the current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))
Response example
{
	"status_code": 200,
	"request_id": "4126d9dd-e037-9f32-8d56-6d29ab3f9a06",
	"code": null,
	"message": "",
	"output": {
		"task_id": "b476bc4e-35c1-4c4e-a4d9-xxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxxx.png"
		}],
		"submit_time": "2024-11-01 09:50:56.081",
		"scheduled_time": "2024-11-01 09:50:56.104",
		"end_time": "2024-11-01 09:51:22.740",
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Asynchronous call

Request example

Text-to-image

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
from dashscope import ImageSynthesis
import os

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges."


def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# Create an asynchronous task
def create_async_task():
    rsp = ImageSynthesis.async_call(api_key=os.getenv("DASHSCOPE_API_KEY"),
                                    model=ImageSynthesis.Models.wanx_v1,
                                    prompt=prompt,
                                    n=1,
                                    style='<watercolor>',
                                    size='1024*1024')
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# Wait for the asynchronous task to complete
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task, api_key=os.getenv("DASHSCOPE_API_KEY"))
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


# Fetch asynchronous task information
def fetch_task_status(task):
    status = ImageSynthesis.fetch(task, api_key=os.getenv("DASHSCOPE_API_KEY"))
    print(status)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))


# Cancel the asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(task):
    rsp = ImageSynthesis.cancel(task, api_key=os.getenv("DASHSCOPE_API_KEY"))
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()

Generation from a reference image

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
from dashscope import ImageSynthesis
import os

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges."

# Method to upload the reference image: choose either a URL or a local path
# If both are provided, the ref_img parameter has higher priority
# Use a public URL
ref_img = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
# Use a local file path
sketch_image_url = './girl.png'

def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# Create an asynchronous task
def create_async_task():
    rsp = ImageSynthesis.async_call(api_key=os.getenv("DASHSCOPE_API_KEY"),
                                    model=ImageSynthesis.Models.wanx_v1,
                                    prompt=prompt,
                                    n=1,
                                    style='<auto>',
                                    size='1024*1024',
                                    ref_mode='repaint',
                                    ref_strength=1.0,
                                    # sketch_image_url=sketch_image_url,
                                    ref_img=ref_img)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# Wait for the asynchronous task to complete
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task, api_key=os.getenv("DASHSCOPE_API_KEY"))
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()
Response example

1. Example response for creating a task

{
	"status_code": 200,
	"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
	"code": "",
	"message": "",
	"output": {
		"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
		"task_status": "PENDING",
		"results": []
	},
	"usage": null
}

2. Example response for querying a task result

{
	"status_code": 200,
	"request_id": "d861d3ba-4b29-9491-abad-266ef4fb2f08",
	"code": null,
	"message": "",
	"output": {
		"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
		}],
		"submit_time": "2024-10-31 20:40:35.631",
		"scheduled_time": "2024-10-31 20:40:35.684",
		"end_time": "2024-10-31 20:41:02.700",
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Java SDK invocation

Synchronous call

Request example

Text-to-image

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
    public static void basicCall() throws ApiException, NoApiKeyException {
        String prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges.";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<watercolor>")
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void listTask() throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public void fetchTask() throws ApiException, NoApiKeyException {
        String taskId = "your task id";
        ImageSynthesis is = new ImageSynthesis();
        // If the DASHSCOPE_API_KEY environment variable is set, apiKey can be null.
        ImageSynthesisResult result = is.fetch(taskId, null);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args){
        try{
            basicCall();
            //listTask();
        }catch(ApiException|NoApiKeyException e){
            System.out.println(e.getMessage());
        }
    }
}

Similar image generation

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.HashMap;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void syncCall() {
        String prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges.";
        // Use a public URL
        String refImage = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png";
        HashMap<String,Object> parameters = new HashMap<>();
        parameters.put("ref_strength", 0.5);
        parameters.put("ref_mode", "repaint");

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<auto>")
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.syncCall();
    }

}
Response example
{
	"request_id": "150edcda-05d5-9ffe-8803-84626d1db623",
	"output": {
		"task_id": "f2098ff0-146e-404c-bb25-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
		}],
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Asynchronous call

Request example

Text-to-image

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }


    /**
     * Create an asynchronous task
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges.";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<watercolor>")
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * Wait for the asynchronous task to complete
     * @param taskId task id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // After configuring the environment variable, you can set apiKey to null here.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        System.out.println(JsonUtils.toJson(result.getOutput()));
    }


    public static void main(String[] args){
        Main main = new Main();
        main.asyncCall();
    }
}

Similar image generation

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }


    /**
     * Create an asynchronous task
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "Close-up shot, 18-year-old Chinese girl, ancient costume, round face, looking at the camera, elegant ethnic clothing, commercial photography, outdoor, cinematic lighting, bust shot, delicate light makeup, sharp edges.";
        String refImage = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<auto>")
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * Wait for the asynchronous task to complete
     * @param taskId task id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.asyncCall();
    }
}
Response example

1. Example response for creating a task

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2. Example response for querying a task result

{
	"request_id": "c44213ba-7aa3-91e4-97c1-c527ade82597",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
		}],
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Error codes

If a model call fails and returns an error message, see Error messages for a solution.

FAQ

Model billing and rate limiting

Free quota

  • Description: The free quota applies only to successfully generated output images. Input images or failed model processing do not consume the free quota.

  • How to get: It is automatically granted when you activate Model Studio. Valid for 90 days.

  • Account scope: Shared between your Alibaba Cloud account and its RAM users.

  • For more details, see Free quota for new users.

Limited-time free trial

  • If billing shows a limited-time free trial, the model is in public preview. You cannot use the model after the free quota runs out.

Billing details

  • If a clear unit price is shown — for example, CNY 0.2 per second — the model is commercially available. You must pay after the free quota expires or is fully consumed.

  • Billing scope: Charges apply only to successfully generated output images. Other scenarios are not billed.

  • Billing method: Billing is applied to your Alibaba Cloud account. RAM users cannot be billed independently. Your Alibaba Cloud account must cover all associated charges. To view billing information, go to the Bills page.

  • Recharge: Go to the Expenses and Costs console.

  • View invocation metrics: Go to the Monitoring page.

  • For more billing questions, see Billing Items.

Rate limiting

  • Rate limit scope: Shared between your Alibaba Cloud account and its RAM users.