Text-to-image

更新时间:
复制 MD 格式

Generate images from text descriptions with the text-to-image API. This service, provided by Alibaba Cloud Model Studio, features the Wan, Qwen-Image, and Z-Image model families.

Try it online: Beijing | Singapore

Model performance

Qwen-Image

Complex layout

image (10)-2026-03-10-15-57-40

Long paragraph

image (11)-2026-03-10-15-57-40

Realistic portrait

image (13)-2026-03-10-15-57-39

Natural landscape

image (12)-2026-03-10-15-57-39

Logical architecture

image (14)-2026-03-10-15-57-38

E-commerce poster

fcd74cd8-c0f6-454b-93b1-e95f337127af-2026-03-10-16-25-42

Prompts

Complex layout: A winter city street scene in Beijing. Two adjacent traditional Chinese shops with bluish-gray roof tiles and vermilion exterior walls stand side by side. Warm-light lanterns with paper-cut horse motifs hang under the eaves, casting soft halos on the damp cobblestone pavement under the diffuse light of an overcast day. To the left is a calligraphy shop. Its aged, indigo-blue signboard bears the bold running script Text rendering. A vertical sign hangs on the shop's glass window, written from top to bottom in Tian Yingzhang's hard-pen style: Professional Slides, Bilingual Posters, Advanced Infographics, with a red cinnabar seal that reads 1k token. Inside the shop, three vertical calligraphy works are faintly visible on the wall. The first reads Alibaba, the second Qwen, and the third image generation. A white-haired elderly man stands with his back to the camera, admiring them. To the right is a flower shop with a signboard that spells out Real texture using fresh flowers. Inside, multi-tiered shelves display red roses, pink peonies, and green plants. A circular, flower-bordered sign on the door reads 2k resolution, and a colorful neon sign by the entrance says Fine Detailing: People, Nature, Architecture. Between the two shops, a snowman holds an old-fashioned small blackboard with chalk writing that announces, Qwen-Image-2.0 Officially Released. To the left on the street, a young couple nestles together. The woman, who has a slim face, wears an off-white cashmere coat and nude-colored leggings. She holds a heart-shaped transparent balloon with the white text Image generation + editing in one printed on it. Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool coat over a light-colored turtleneck sweater. To the right on the street, a delivery rider with smaller model, faster speed written on his back speeds past. The entire street is an interplay of light and shadow, balancing motion and stillness.

Long paragraph: A classical Chinese ink wash scroll, vertical composition. The full text of Liu Yong’s poem Yulinling · Cold Cicadas Wail is written from top to bottom, right to left, in running script (12 lines, including punctuation and line breaks): Cold cicadas wail, dusk falls at the pavilion, sudden rain just stops. At the city gate, we drink without joy, lingering as the orchid boat urges departure. Holding hands, we gaze tearfully, speechless, choked with sobs. Thinking of the journey ahead—thousands of miles of misty waves, vast and dim, the southern sky stretches wide. Since ancient times, the sentimental grieve at parting. How much more unbearable on this desolate autumn day! Where will I wake tonight, drunk? By the willow-lined shore, dawn breeze, and the waning moon. After this year, even fine days and beautiful scenes will be meaningless. Even if I have a thousand feelings, to whom can I speak them? The calligraphy's ink tones are varied and harmonious, with natural dry-brush effects. The brushwork is vigorous yet graceful, and the flow of characters is as fluid as running water. The characters show a slight ink bleed, mimicking the absorbent effect of Xuan paper. The background is a minimalist ink wash landscape that evokes a poetic mood: in the lower-right corner, a lone boat is moored on a shallow bank, its bow slightly upturned, a rope loosely tied to a withered willow. In the distance to the left, faint ink washes depict layers of low-hanging evening mist and the vast Chu sky, with a hint of a bluish-gray mountain range on the horizon. In the foreground, two or three slender willow branches jut out from the bank, their leaves sparse, capturing the bleakness of late autumn. At the tips of the willows hangs a barely visible waning moon, its cold light illuminating the traces of a morning breeze in the thin mist (suggested by a few gentle wisps of willow and ripples on the water). The entire painting has a profound and timeless atmosphere, melancholic but not despairing, strictly adhering to the artistic conception of Song-dynasty poetry and the traditional literati paradigm of poetry, calligraphy, and painting as one. There are no seals, no colophons, and no modern elements.

Realistic portrait: A young Asian woman in her early twenties with blunt bangs and long, sleek black hair that falls naturally over her shoulders. She is sitting sideways on a vintage floral-print sofa. The sofa's fabric, an off-white base with pink and green flowers, looks slightly worn and lived-in. She is wearing a loose-fitting, light green mohair sweater with a soft, fluffy texture, paired with a light grayish-blue linen maxi skirt, creating a fresh, natural, and leisurely look. In her right hand, she casually holds a red tomato near her chin, her pose relaxed. She gazes directly at the camera with a calm, slightly aloof expression, conveying a sense of nonchalant detachment. To the right of the sofa, a light-colored ceramic plate holds three or four plump, bright red tomatoes with green stems, their vibrant color creating a strong contrast with the overall cool green tones of the image. The background is a distressed, textured teal-green wall. Natural light streams in from a window, creating distinct beams that fall diagonally across the subject and the background, adding rich layers of light and shadow. Several potted plants are placed on the windowsill and in the corners of the background, and a dark brown antique wooden cabinet is faintly visible on the left. The photograph has a cool green color palette, with noticeable film grain and subtle light leak effects. The composition is full, and the atmosphere is quiet and artistic, strongly evoking the style of vintage film-based portrait photography.

Natural landscape: A realistic summer forest scene. In the center is a deep, serene clearing. Towering oak and beech trees form the main canopy, their dense crowns a deep, rich emerald green with a subtle waxy sheen on the leaves. Soft but intense sunlight filters through gaps in the canopy, forming clear Tyndall beams in the air. These beams have a warm golden hue at the edges, creating a subtle contrast with the cool green shadows. In the mid-ground, a cluster of young maple saplings unfurls its bright, vivid green leaves, which are translucent with clearly visible veins and slightly curled edges, as if freshly washed by morning dew. In the foreground to the left, low-growing holly and viburnum shrubs are covered in a soft, matte olive-green foliage with intricate, fine textures. The undersides of some leaves show a pale gray-green. The ground is covered with a thick, moist layer of moss composed of various species: up close, velvety hanging moss appears a lush, moist green, with tiny dewdrops on its surface; further away, scale moss and peat moss blend in shades of bluish-gray-green and brownish-green. The underlying layer of leaf litter is faintly visible, a mixture of deep brown and dark green organic textures. All vegetation has a natural, slightly wet sheen, and extremely fine suspended particles float in the beams of light. The background forest area gradually blurs, maintaining a sense of layers without distracting from the main subject, and a thin layer of blue-green mist is visible in the distance. The overall lighting suggests the oblique sunlight of around 10 a.m., with moderate contrast between light and shadow. The color green is expressed through more than 23 distinct variations in brightness, saturation, temperature, and texture (such as waxy, velvety, leathery, and gelatinous), with no repetition, creating a lush, breathing, and biologically detailed and ecologically authentic secret summer forest.

Logical architecture: In the center-left of the image is the main title in large, bold black text: "OKR work method." Directly below it, in a slightly smaller font, is "Enhancing Team Efficiency." Four lines with arrows radiate from this central text to four modules: "Implementation process" (top right), "Efficiency-boosting mechanism" (middle right), "Common challenges" (bottom right), and "Key principles" (bottom left). In the top-left corner, a red-bordered rectangle contains the title "Objective (O)" with three lines of small text below: "Highly motivating | Clear and tangible |", "Answers 'What do we want to achieve?'" A black arrow labeled "[Drive]" points from this box to the text "Core structure" on the right. Directly below is a blue-bordered rectangle with the title "Key Results (KR)" and three lines of small text below: "2-5 | Measurable |", "Time-bound | Challenging |", "Answers 'How to prove we achieved the goal?'" Another black arrow labeled "[Measure]" also points from this box to "Core structure." The bolded text "Core structure" is located directly above the central title, with a red arrow pointing down to "OKR work method." The "Implementation process" module in the top-right area contains three horizontally aligned rectangular boxes connected by solid black arrows from left to right: - The first, a red-bordered box, is titled "Set & Align Objectives" with the text "Vertical & horizontal alignment" below. - The second, a blue-bordered box, is titled "Periodic Execution & Tracking" with the text "Weekly Meetings | Dashboard | Transparency" below. - The third, a gray-bordered box, is titled "Review & Retrospective" with the text "Learning > Assessment | Continuous Optimization" below. The "Efficiency-boosting mechanism" module in the middle right contains three ellipses arranged horizontally and connected by dashed lines: - The left ellipse is titled "Focus on Priorities:" with the text "1-3 Os | Do the right things, not just everything" below. - The middle ellipse is titled "Enhance Transparency & Collaboration:" with the text "Company-wide OKRs public | Break down departmental silos" below. - The right ellipse is titled "Stimulate Autonomy & Accountability:" with the text "Participatory formulation | Achievement-driven intrinsic motivation" below. The "Common challenges" module in the bottom right contains two parallel red-bordered boxes: - The upper box contains "Goal Setting Imbalance" with two lines of text below: "All KRs at 0.3 or all at 1.0 → Adopt 0.7 as the ideal split." To the right is a red 'X' and the text "× Strictly prohibited to link to compensation." - The lower box contains "OKR ≠ Performance appraisal." To the far right of this module, a separate ellipse contains the text "Distinguish KPI (for evaluation/reward) from OKR (for development/alignment)," next to a stick-figure drawing of a person with glasses holding a red marker. The "Key principles" module in the bottom left presents four principles in a vertical list, each preceded by a colored solid dot: - Red dot: "Directional × Result-oriented" - Blue dot: "Challenging × Feasible" - Black dot: "Transparent × Autonomous" - Green dot: "Cyclical × Learning-oriented".

E-commerce poster: A high-quality, C4D-style e-commerce poster with a fresh blue color scheme. At the top, massive 3D artistic text reads, Tmall Double 11 pre-sale is here, creating a strong visual impact. The centerpiece is a blue bag of Moe Pet Paradise pet food. The bag has a transparent window showing tempting meat chunks inside, and a cute 3D-modeled cat is next to it. The scene is dotted with delicate small animal models and blue, futuristic mechanical devices, creating a lively promotional atmosphere. At the bottom, a prominent red 3D text announces, Get ¥99 off on orders over ¥399. Bright commercial studio lighting, ultra-high definition, detailed rendering, transparent textures, and rigorous composition.

Wanxiang

Portrait photography

p1023408

Photorealistic photography

p1023409

Artistic styles

p1023411

Text rendering

p1023399

Poster design

image.png

Image set generation

p1023424

View prompt

Portrait photography: A realistic portrait photograph. Background: the red walls of the Forbidden City. A woman in a black cheongsam holds a fan. Use long-exposure photography to create a cinematic, story-driven feel inspired by Wong Kar-wai. Passersby blur into motion trails, and dreamy lighting creates soft, flowing light paths. Use a soft-focus effect. The woman's gaze is deep and enigmatic, conveying a strong artistic presence.

Photorealistic photography: Photorealistic photography of a fox staring into the lens in a forest. A fisheye perspective creates strong distortion. Fur details are sharp, and background trees are warped into a circular pattern. Watercolor style with soft tones.

Artistic styles: A bouquet of wildflowers in an old earthenware vase. Background: a country kitchen. Impressionist style, soft brushstrokes, warm light, oil painting texture.

Text rendering: Traditional Chinese ink brush painting with visible Xuan paper texture. A light ink wash outlines a hazy living room. An Eastern girl in a plain dress sits cross-legged on a softly blurred vintage fabric sofa, her head lowered as she holds an unrolled poem scroll. Outside, bamboo shadows sway and a light breeze stirs the curtains. The composition has generous white space. On the right, small regular script reads: "Sitting idle, grieving at graying temples; dreams drift into blue smoke." A vermilion seal is in the lower-left corner. Ink tones vary naturally, with dry-brush strokes creating a sense of flowing light and shadow. The mood is serene and profound, evoking the lingering notes of a guqin.

Poster Design: Flat geometric illustration style, a Dragon Boat Festival poster, magazine cover. Color Palette and Background: The main color is a pink gradient, creating a soft and festive background that sets a warm and traditional tone. Text Elements: Green font with a shadow effect. The main copy highlights "DRAGONBOAT FESTIVAL" and "Duanwu" on two separate lines. Below the body text, "2025/05/31" and "the fifth day of the fifth lunar month" highlight the date "2025/05/31". Main Graphic: A dragon boat with a green body and pink fins, in highly saturated colors with strong contrast, surrounded by auspicious cloud elements. There are figures on the boat to further evoke the scene of dragon boat racing and add festive energy. Detail Embellishments: Add the text "Chinese Traditional Festival" paired with small zongzi icons to enrich the cultural details. Advanced minimalist layout, a masterpiece. Simple, stylish, and grand, a new Chinese-style traditional poster. The font should not have a shadow style.

Image set generation: A four-panel, Japanese-style chibi manga in a cel-shading style. Panel 1: A programmer with black-rimmed glasses stares at a red error message on the screen. His pupils shrink in shock as cold sweat drips down. The background cracks and dissolves into a pixelated abyss. Panel 2: He rolls up his sleeves, types confidently, and raises an eyebrow. A speech bubble appears above him: "This is just a five-line code fix!" Panel 3: His screen is flooded with chaotic error symbols. His hair stands on end, dark circles ring his eyes, and his chair tilts back 45 degrees. Discarded flowcharts float across the ceiling. Panel 4: After accidentally deleting a single grayed-out comment line, a green checkmark flashes. He tilts his head in a daze as a question bubble appears on the screen: "...So it was all just a hallucination?"

Model selection

  • wan2.7-image-pro: Offers the most features, including multi-image generation, resolutions up to 4096x4096, and enhanced control over facial features, colors, and long text rendering.

  • qwen-image-2.0-pro: Excels at accurately rendering Chinese and English text that blends naturally with physical materials. Ideal for creating charts, posters, and presentations.

  • z-image-turbo: Delivers fast, cost-effective image generation, excelling at highly realistic portraits and product images.

Quick start

Prerequisites

Before you begin, get an API key, then set the API key as an environment variable. If you use the DashScope SDK, you must also install the SDK.

Sample code

Calling methods:

Wan - asynchronous call

Python

Request example
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# This is the base URL for the China (Beijing) region; base URLs are region-specific.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

# If the environment variable is not set, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys vary by region. To get an API key, visit: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")


def main():
    message = Message(
        role="user",
        content=[
            {"text": "A young woman in a natural, casual selfie style. An ultra-high-definition, realistic lifestyle photo. She is wearing a yellow floral long-sleeved top, and her long, slightly wavy hair falls naturally. The background is an outdoor natural scene with green plants nearby and water and mountains in the distance. Soft, natural sunlight falls on her face and body, creating natural light and shadow effects. The camera angle is a medium shot from a selfie perspective, as if held by her. She is standing naturally, projecting a relaxed and comfortable state. The angle is natural, in the style of a casual snapshot—an unguarded moment."}
        ]
    )
    
    # Submit an asynchronous task.
    print("Submitting the asynchronous task...")
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        enable_sequential=False,
        n=1,
        size="2K"
    )
    
    if response.status_code == 200:
        print(f"Task submitted successfully. Task ID: {response.output.task_id}")
        
        # Wait for the task to complete.
        status = ImageGeneration.wait(task=response, api_key=api_key)
        
        if status.output.task_status == "SUCCEEDED":
            print("Task completed!")
            print(f"Result:")
            print(status)
        else:
            print(f"Task failed. Status: {status.output.task_status}")
    else:
        print(f"Task creation failed: {response.code} - {response.message}")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {e}")
Response example

1. Task creation response

{
    "status_code": 200,
    "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": null,
        "audio": null,
        "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
        "task_status": "PENDING"
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0
    }
}

2. Task status query response

The image URL is valid for 24 hours. Download the image promptly.
{
    "status_code": 200,
    "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-03-31 23:04:46.166",
        "scheduled_time": "2026-03-31 23:04:46.208",
        "end_time": "2026-03-31 23:05:11.664",
        "finished": true
    },
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "characters": 0,
        "size": "2048*2048",
        "total_tokens": 731,
        "image_count": 1
    }
}

Java

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.Collections;

public class Main {

    static {
        // This is the base URL for the China (Beijing) region; base URLs are region-specific.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // If the environment variable is not set, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // API keys vary by region. To get an API key, visit: https://help.aliyun.com/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static ImageGenerationResult waitTask(String taskId)
            throws ApiException, NoApiKeyException {
        ImageGeneration imageGeneration = new ImageGeneration();
        return imageGeneration.wait(taskId, apiKey);
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException {
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "A young woman in a natural, casual selfie style. An ultra-high-definition, realistic lifestyle photo. She is wearing a yellow floral long-sleeved top, and her long, slightly wavy hair falls naturally. The background is an outdoor natural scene with green plants nearby and water and mountains in the distance. Soft, natural sunlight falls on her face and body, creating natural light and shadow effects. The camera angle is a medium shot from a selfie perspective, as if held by her. She is standing naturally, projecting a relaxed and comfortable state. The angle is natural, in the style of a casual snapshot—an unguarded moment.")
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(false)
                .n(1)
                .size("2K")
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult taskResult = null;
        try {
            System.out.println("----async call, creating task----");
            taskResult = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("Task created: " + JsonUtils.toJson(taskResult));

        // Wait for the task to complete.
        String taskId = taskResult.getOutput().getTaskId();
        ImageGenerationResult result = waitTask(taskId);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            asyncCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
    }
}
Response example

1. Task creation response

{
    "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx",
    "output": {
        "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
        "task_status": "PENDING"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

2. Task status query response

{
    "requestId": "daea7295-4ce0-928a-9a11-4d2bea058xxx",
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "total_tokens": 731,
        "image_count": 1,
        "size": "2048*2048"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
        "task_status": "SUCCEEDED",
        "finished": true,
        "submit_time": "2026-03-31 19:49:53.124",
        "scheduled_time": "2026-03-31 19:49:53.175",
        "end_time": "2026-03-31 19:50:53.160"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Curl

Note
  • For an asynchronous call, you must set the Header parameter X-DashScope-Async to enable.

  • The task_id of an asynchronous task can be queried for 24 hours. After this period, the task status changes to UNKNOWN.

  • This method works for all models. For beginners, we recommend using Postman to call the API.

Step 1: Create a task

The request returns a task ID (task_id).

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "X-DashScope-Async: enable" \
--data '{
    "model": "wan2.7-image-pro",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {"text": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"}
                ]
            }
        ]
    },
    "parameters": {
        "size": "2K",
        "n": 1,
        "watermark": false,
        "thinking_mode": true
    }
}'
Step 2: Query task result

Use the task_id from the previous step to poll the API for the task status until the task_status changes to SUCCEEDED or FAILED.

Replace {task_id} with the task_id value returned by the previous API call. The task_id is valid for queries for 24 hours.

curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Qwen - synchronous call

Python

Request example

import json
import os
import dashscope
from dashscope import MultiModalConversation

# Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

messages = [
    {
        "role": "user",
        "content": [
            {"text": "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow."}
        ]
    }
]

# API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-2.0-pro",
    messages=messages,
    result_format='message',
    stream=False,
    watermark=False,
    prompt_extend=True,
    negative_prompt="Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
    size='2048*2048'
)

if response.status_code == 200:
    print(json.dumps(response, ensure_ascii=False))
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("See documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code")

Response example

Image URLs expire after 24 hours. Download the images promptly.
{
    "status_code": 200,
    "request_id": "d2d1a8c0-325f-9b9d-8b90-xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "width": 2048,
        "image_count": 1,
        "height": 2048
    }
}

Java

Request example

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class QwenImage {

    static {
        // Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
    // If you haven't set the environment variable, replace the line below with: static String apiKey ="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {

        MultiModalConversation conv = new MultiModalConversation();

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("text", "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow.")
                )).build();

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("prompt_extend", true);
        parameters.put("negative_prompt", "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.");
        parameters.put("size", "2048*2048");

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model("qwen-image-2.0-pro")
                .messages(Collections.singletonList(userMessage))
                .parameters(parameters)
                .build();

        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Response example

Image URLs expire after 24 hours. Download the images promptly.
{
    "requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
    "usage": {
        "image_count": 1,
        "width": 2048,
        "height": 2048
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    }
}

Curl

Request example
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-2.0-pro",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "text": "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow."
                    }
                ]
            }
        ]
    },
    "parameters": {
        "negative_prompt": "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
        "prompt_extend": true,
        "watermark": false,
        "size": "2048*2048"
    }
}'
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-2.0-pro",
    "input": {
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "text": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."
            }
          ]
        }
      ]
    },
    "parameters": {
      "negative_prompt": "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
      "prompt_extend": true,
      "watermark": false,
      "size": "2048*2048"
    }
}'
Response example
{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ]
    },
    "usage": {
        "height": 2048,
        "image_count": 1,
        "width": 2048
    },
    "request_id": "d0250a3d-b07f-49e1-bdc8-6793f4929xxx"
}

Key capabilities

1. Prompt following

Parameters: messages.content.text or input.prompt (required), and negative_prompt (optional).

  • prompt: Describes the desired content for the image, including the subject, scene, style, lighting, and composition. This is the core parameter for controlling text-to-image generation.

  • negative prompt: Describes what to exclude from the image, such as "blurry" or "extra fingers." This parameter helps refine the output quality.

For best results, use a structured prompt. For more information, see Text-to-image prompt guide.

The negative_prompt parameter is not supported by wan2.7-image-pro and wan2.7-image. To exclude unwanted elements, describe them in the prompt (for example, "do not include xxx").

2. Enable prompt rewriting

Parameter: parameters.prompt_extend (Boolean, defaults to true).

This feature automatically expands and optimizes short prompts to improve image quality. Enabling this feature adds 3 to 5 seconds to the generation time, as a large model is used to rewrite the prompt.

Recommendations:

  • Enable this feature for brief or general prompts to significantly improve image quality.

  • Disable this feature if you need precise control over image details, have provided a comprehensive prompt, or if response latency is a concern. To disable it, set the prompt_extend parameter to false.

The prompt_extend parameter is not supported by wan2.7-image-pro and wan2.7-image. To improve image quality for these models, enable thinking_mode instead.

3. Set the output image resolution

Parameter: parameters.size (string), in the "width*height" format.

Model

Size format

Pixel range

Default

Aspect ratio

wan2.7-image-pro

Shorthand

1K (1024*1024), 2K (2048*2048), 4K (4096*4096)

2K (2048*2048)

1:8 – 8:1

Custom "width*height"

768*768 – 4096*4096

wan2.7-image

Shorthand

1K (1024*1024), 2K (2048*2048)

2K (2048*2048)

1:8 – 8:1

Custom "width*height"

768*768 – 2048*2048

wan2.6-image (interleaved text-image output mode)

Custom "width*height"

768*768 – 1280*1280

Matches input aspect ratio (≤1280*1280)

1:4 – 4:1

wan2.6-t2i, wan2.5-t2i-preview

Custom "width*height"

1280*1280 – 1440*1440

1280*1280

1:4 – 4:1

wan2.2 and earlier t2i models

Custom "width*height"

[512, 1440], and total pixels ≤1440*1440

1024*1024

-

qwen-image-2.0 series

Custom "width*height"

512*512 – 2048*2048

2048*2048

-

qwen-image-max / qwen-image-plus series

Fixed preset sizes only

See preset sizes below

1664*928 (16:9)

-

The wan2.7-image-pro model supports 4K resolution and custom resolutions up to 4096*4096, but only for text-to-image tasks (where no image is input and image set generation is disabled). All other scenarios are limited to 2K resolution (2048*2048).

The qwen-image-max and qwen-image-plus series support only the following five fixed resolutions:

  • 1664*928 (default): 16:9

  • 1472*1104: 4:3

  • 1328*1328: 1:1

  • 1104*1472: 3:4

  • 928*1664: 9:16

Recommended resolutions:

Aspect ratio

4K (wan2.7-image-pro)

2K (wan2.7-image, qwen-image-2.0)

1K (Wan t2i)

1:1

4096*4096

2048*2048

1280*1280

16:9

4096*2304

2688*1536

1696*960

9:16

2304*4096

1536*2688

960*1696

4:3

4096*3072

2368*1728

1472*1104

3:4

3072*4096

1728*2368

1104*1472

4. Image set generation

Parameter: parameters.enable_sequential (Boolean, defaults to false). Supported only by wan2.7-image-pro and wan2.7-image.

Set to true to enable image set generation mode. In this mode, the model uses the prompt and any reference images to generate multiple, story-coherent images from a single request.

  • Number of images: Controlled by the n parameter. When this mode is enabled, this value can range from 1 to 12, with a default of 12. The model determines the actual number of images it generates, which will not exceed n.

  • Note: When image set generation is enabled, the thinking_mode and color_palette parameters are unavailable.

5. Thinking mode

Parameter: parameters.thinking_mode (Boolean, defaults to true). Supported only by wan2.7-image-pro and wan2.7-image.

When enabled, the model enhances its reasoning capabilities to improve image quality. This increases the generation time.

Available only when image set generation is disabled (enable_sequential=false).

6. Custom color palette

Parameter: parameters.color_palette (array). Supported only by wan2.7-image-pro and wan2.7-image.

Define the image's color scheme by providing an array of objects, where each object specifies a hex color and its ratio. You must provide 3 to 10 colors (8 is recommended), and the sum of all ratios must equal 100.00%.

Available only when image set generation is disabled (enable_sequential=false).

Click to view an input example

"color_palette": [
    {
        "hex": "#C2D1E6",
        "ratio": "23.51%"
    },
    {
        "hex": "#CDD8E9",
        "ratio": "20.13%"
    },
    {
        "hex": "#B5C8DB",
        "ratio": "15.88%"
    },
    {
        "hex": "#C0B5B4",
        "ratio": "13.27%"
    },
    {
        "hex": "#DAE0EC",
        "ratio": "10.11%"
    },
    {
        "hex": "#636574",
        "ratio": "8.93%"
    },
    {
        "hex": "#CACAD2",
        "ratio": "5.55%"
    },
    {
        "hex": "#CBD4E4",
        "ratio": "2.62%"
    }
]

Production deployment

  • Fault tolerance

    • Handling rate limiting: When the API returns the Throttling error code or the HTTP 429 status code, rate limiting has been triggered. To handle rate limiting, see Rate Limiting.

    • Polling for asynchronous tasks: When polling for the result of an asynchronous task, implement a reasonable polling strategy to avoid triggering rate limiting. For example, poll every 3 seconds for the first 30 seconds, then increase the polling interval. Set a final timeout for the task (e.g., 2 minutes). If the task times out, mark it as failed.

  • Risk prevention

    • Persist results: The API's image URLs are valid for 24 hours. Your production system must download the image immediately after receiving the URL and transfer it to your own persistent storage service, such as Alibaba Cloud Object Storage Service (OSS).

    • Content moderation: All prompt and negative_prompt inputs are subject to content moderation. If the input is non-compliant, the request is blocked and a DataInspectionFailed error is returned.

    • Copyright and compliance risks of generated content: Ensure that your prompts comply with all applicable laws and regulations. Generating content that includes brand trademarks, celebrity likenesses, or copyrighted intellectual property (IP) may pose infringement risks. You are responsible for evaluating and bearing all associated risks.

API reference

Billing and rate limiting

Error codes

If the model call fails and returns an error message, see Error codes for resolution.

FAQ

Q: How long are image URLs valid? How do I save images permanently?

A: Image URLs expire after 24 hours. You must programmatically download the image immediately and save it to persistent storage, such as a local server or Alibaba Cloud Object Storage Service.

Q: My API call returns a DataInspectionFailed error. How do I resolve this?

A: This error means your input triggered content moderation. Review your prompt or negative_prompt, remove any non-compliant content, and then retry the request.

Q: When should I enable or disable the prompt_extend parameter?

A: Keep it enabled (the default) for concise prompts or for more creative output. Set it explicitly to false when your prompt is already detailed and specialized, or when you are sensitive to API latency.

Note: The wan2.7-image-pro and wan2.7-image models do not support the prompt_extend parameter. To improve image quality, enable thinking_mode instead.