Skip to main content

Wanxiang - Sketch to Image API Reference

This topic describes the API input and output parameters for the Wanxiang - Sketch to Image model.

Related guide: Sketch to image
This document applies only to the China (Beijing) region. Use an API key from this region.
Alibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from https://dashscope.aliyuncs.com to the new domain.{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.

Model overview

Example output
image
Model introduction

Model

Model introduction

wanx-sketch-to-image-lite

Wanx-Sketch-to-Image generates exquisite sketch artworks based on hand-drawn patterns and text descriptions.

Model description

Model

Unit price

Rate limiting (shared by primary account and RAM sub-accounts)

Free quota(View)

QPS limit for task creation API

Number of concurrently processing tasks

wanx-sketch-to-image-lite

0.06 CNY/image

2

1

500 images

For more information, see Model billing and rate limiting.

Prerequisites

The Sketch-to-Image API supports calls over HTTP and through the DashScope SDK. Before calling the API, you need to obtain and configure an API Key, and then configure the API Key in environment variables. To call the API through the SDK, please install the DashScope SDK. Currently, the SDK supports Python and Java.

HTTP calls

Image models take a long time to process. To avoid request timeouts, HTTP calls only support retrieving model results asynchronously. You need to make two requests:
  1. Create a task to obtain the task ID: First send a task creation request, which returns a task ID (task_id).
  2. Query results by task ID: Use the task ID obtained in the previous step to query the task status and results. When the task succeeds, an image URL is returned, valid for 24 hours.
After a task is created, it is added to a queue and waits to be scheduled. You then need to call the "Query results by task ID" API to obtain the task status and results.

Step 1: Create a task to obtain the task ID

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

Request parameters

Request headers
Content-Typestring (Required)Request content type. This parameter must be set to application/json.Authorization string (Required)Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.X-DashScope-Asyncstring (Required)Asynchronous processing configuration parameter. HTTP requests only support asynchronous mode and must be set to enable.
If this request header is missing, the following error is returned: "current user api does not support synchronous calls".
X-DashScope-WorkSpacestring (Optional)The workspace ID of Alibaba Cloud Model Studio. Example value: llm-xxxx.You can obtain the Workspace ID here.
This parameter is filled in based on the Alibaba Cloud Model Studio API Key.
  • If it is a primary account API Key, it can be left empty. If left empty, primary account permissions are used; if filled in, the permissions of the corresponding workspace are used.
  • If it is a RAM sub-account API Key, it is required. A RAM sub-account always belongs to a workspace.
The workspace must have permission to access the model in order to call the API. If you do not have permission, see Authorize sub-workspaces to call, train, and deploy models.
For how to distinguish between Alibaba Cloud Model Studio primary accounts and RAM sub-accounts, see Primary account management.
Request Body
modelstring(Required)The model to call.inputobject(Required)Basic input information, such as the prompt and the image URL address.

Properties

promptstring(Required)The prompt, used to describe the elements and visual features expected to be included in the generated image.Supports Chinese and English, with a length of no more than 75 characters; the excess is automatically truncated.Example value: a towering tree.sketch_image_urlstring(Required)The URL address of the input sketch. The input sketch must have the same aspect ratio as the output image resolution; otherwise, the image may be stretched or distorted. Using a white background image is recommended.The URL must be a publicly accessible address and support the HTTP or HTTPS protocol. You can also obtain a temporary public URL here.Image limits:
  • Image formats: JPG, JPEG, PNG, TIFF, WEBP.
  • Image resolution: no less than 256×256 pixels and no more than 2048×2048 pixels.
  • Image size: no more than 10 MB.
  • The URL address must not contain Chinese characters.
Sketch example:image
parametersobject (Optional)Image processing parameters.

Properties

stylestring (Optional)The style of the output image. The following style values are currently supported:
  • <auto>: Default value. The model outputs the image style randomly.
  • <3d cartoon>: 3D cartoon.
  • <anime>: Anime.
  • <oil painting>: Oil painting.
  • <watercolor>: Watercolor.
  • <sketch>: Sketch.
  • <chinese painting>: Chinese painting.
  • <flat illustration>: Flat illustration.
sizestring (Optional)The resolution of the output image. Only one image resolution is currently supported: 768*768, which is also the default value.ninteger (Optional)The number of images to generate. The value range is 1~4, and the default is 4.sketch_weightinteger (optional)The degree to which the input sketch constrains the output image.The value range is 0-10, with an interval of 1, and the default value is 10. A larger value indicates that the output image is more similar to the input sketch.sketch_extractionboolean (optional)If the uploaded image is an RGB image rather than a sketch (sketch line drawing), this parameter controls whether to perform sketch edge extraction on the input image.The default value is False, which means no extraction is performed. When set to True, extraction is performed, and the sketch_color field becomes invalid.sketch_colorarray (optional)This field takes effect when sketch_extraction=false. The values it contains are all treated as brush colors, and all other values are treated as background colors. The model generates a new painting based on the areas depicted in one or more brush colors. The default value is [].When the lines in the sketch_image_url line drawing are not black but contain one or more other colors, you can specify one or more RGB color values as brush colors.Example value: [[134, 134, 134], [0, 0, 0]]
  • curl
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-sketch-to-image-lite",
    "input": {
        "sketch_image_url": "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg",
        "prompt": "一棵参天大树"
    },
    "parameters": {
        "size": "768*768",
        "n": 2,
        "sketch_weight": 3,
        "style": "<watercolor>"
    }
}'

Response parameters

outputobjectTask output information.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
request_idstringUnique request identifier for tracing and troubleshooting.codestringError code. Returned only for failed requests. See Error codes.messagestringDetailed error message. Returned only for failed requests. See Error codes.
  • Successful response
  • Error response
Please save the task_id, which is used to query the task status and results.
{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Step 2: Query the result by task ID

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

Request parameters

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.
  • Query task results
Please replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task_id.
If you use a model in the Singapore region, you need to replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} must be replaced with the 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"

Response parameters

outputobjectTask output information.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
task_metrics objectStatistics for the task result.

Properties

TOTAL integerThe total number of tasks.SUCCEEDED integerThe number of successful tasks.FAILED integerThe number of failed tasks.
results array of objectThe list of task results, including image URLs, error messages in case of partial task failure.
{
    "results": [
        {
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}
codestringError code. Returned only for failed requests. See Error codes.messagestringDetailed error message. Returned only for failed requests. See Error codes.
usage objectThe output statistics. Only successful results are counted.

Properties

image_count integerNumber of images successfully generated. Billing: Cost = Number of images × Unit price.
request_idstringUnique request identifier for tracing and troubleshooting.
  • Success response
  • Failure response
  • Partial failure 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
    }
}

DashScope SDK invocation

Install the latest DashScope SDK. See Install the SDK. The DashScope SDK supports Python and Java. SDK parameter names are mostly consistent with the HTTP API. Parameter structure varies by SDK language. For details, see the HTTP Invocation section. Because image models take a long time to process, the underlying service is asynchronous. The SDK supports both synchronous and asynchronous calls.

Python SDK invocation

  • Synchronous call
  • Asynchronous invocation
Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "一棵参天大树"
sketch_image_url = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg"
model = "wanx-sketch-to-image-lite"

print('----sync call, please wait a moment----')
try:
    job = client.images.generate(
        model=model,
        prompt=prompt,
        n=1,
        style='<watercolor>',
        size='768*768',
        # 模型专属输入字段(sketch_image_url)经 extra_input 并入请求 input 段
        extra_input={'sketch_image_url': sketch_image_url})
    print('response: %s' % job)
    # save file to current directory
    for url in job.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Response example
{
    "request_id": "4126d9dd-e037-9f32-8d56-6d29ab3f9a06",
    "task_id": "b476bc4e-35c1-4c4e-a4d9-xxxxxxx",
    "status": "SUCCEEDED",
    "results": [{
        "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxxx.png"
    }],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK invocation

  • Synchronous call
  • Asynchronous invocation
Request example
// 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 syncCall() {
        String prompt = "一棵参天大树";
        String sketchImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg";
        String model = "wanx-sketch-to-image-lite";
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .model(model)
                .prompt(prompt)
                .n(1)
                .size("768*768")
                .sketchImageUrl(sketchImageUrl)
                .style("<watercolor>")
                .build();

        String task = "image2image";
        ImageSynthesis imageSynthesis = new ImageSynthesis(task);
        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
	}
}

Error codes

If the model call fails, the HTTP interface returns an HTTP status code and error code (when a Python SDK 2.0 call fails, a DashScopeError exception is thrown, and you can obtain the corresponding information through the exception properties e.status_code/e.code/e.message/e.request_id). For common error codes, see Error codes for troubleshooting. This API also has specific status codes, as described in the following table.

HTTP status code

API error code (code)

API error message (message)

Description

400

InvalidParameter.DataInspection

Unable to download the media resource during the data inspection process.

Failed to download the input image. Check your network connection or the input format.

400

InvalidParameter

Value error, format of image {url} is not valid : payload.input.sketch

The uploaded image size does not meet the requirements.

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.