Skip to content

Wan-Image Generation and Editing 2.7 API Reference

Reference, synced 2026-06-13.

flowchart TD
  n0["Models"]
  n1["Overview"]
  n2["Products"]
  n3["Solutions"]
  n4["Pricing"]
  n5["Resources"]
  n6["Partners"]
  n7["Support"]
  n8["Language"]
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n3 --> n4
  n4 --> n5
  n5 --> n6
  n6 --> n7
  n7 --> n8

Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works

Models

Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.

Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.

Try Visual Model \ Supports image understanding, image generation, and video generation.

Models

HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt

Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance

Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support

Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning

GenAI Application

Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.

AI Service

Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.

AI Use Case

AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.

AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.

Overview

As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.

Why Alibaba Cloud

About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.

Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure

Customers and Insights

Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud

What's New

Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases

Products

Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack

Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users

Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime

Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need

Solutions

Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions

Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability

New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey

Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech

Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies

Pricing

Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.

Overview & Tools

Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.

Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing

Optimize your cost

Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos

Resources

Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.

Technical Resources

Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI

Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology

Training&Certification

Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.

Developer Hub

Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community

Partners

Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.

Marketplace

AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner

Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs

Find a Partner

Partner Hub \ Find your ideal partner in no time

Become a Partner

Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs

Support

Full-lifecycle support and expert services, from cloud advisory and migration to operations.

Support & Professional Services

Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise

Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution

Contact us

Connect With Us \

Talk to a sales expert and get a custom quote for your business

Language

  • English
  • 简体中文
  • 繁體中文
  • 日本語
  • Bahasa Indonesia

Locale

Visit aliyun.com

Documentation

Alibaba Cloud Model Studio

User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)

Search for Help Content

Getting Started

The Beginner's Guide

Well-Architected Framework

AI & Machine Learning

Platform For AI

Alibaba Cloud Model Studio

DashVector

Artificial Intelligence Recommendation

OpenSearch

Image Search

Machine Translation

Intelligent Speech Interaction

Optimization Solver

Intelligent Computing LINGJUN

Computing

Elastic Compute Service

Elastic GPU Service

Elastic Container Instance

Dedicated Host

Compute Nest

Simple Application Server

Cloud Box

Auto Scaling

Elastic High Performance Computing

Batch Compute (Deprecated)

Function Compute

Serverless App Engine

ENS

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

Edge Network Acceleration

Alibaba Cloud Linux

AgentBay

Container

Container Service for Kubernetes

Container Compute Service

Container Registry

Storage

Object Storage Service

Cloud Parallel File Storage

File Storage NAS

Tablestore

Storage Capacity Unit

Simple Log Service

Cloud Backup

Intelligent Media Management

Drive and Photo Service

Data Transport

Cloud Storage Gateway

Data Online Migration

Hybrid Cloud Storage Array

Storage Services Overview

Backup and Disaster Recovery Center

Networking and CDN

Server Load Balancer

Elastic IP Address

Internet Shared Bandwidth

Data Transfer Plan

Virtual Private Cloud

NAT Gateway

PrivateLink

Alibaba Cloud DNS PrivateZone

Network Intelligence Service

Cloud Data Transfer

IPv6 Gateway

Anycast Elastic IP Address

Cloud Enterprise Network

Global Accelerator

VPN Gateway

Smart Access Gateway

Express Connect

CDN

Edge Security Acceleration

Cloud Network Well-architected Design Guidelines

Security

Anti-DDoS

Web Application Firewall

Cloud Firewall

Security Center

Bastionhost

Secure Access Service Edge

Certificate Management Service

Key Management Service

Data Security Center

Identity as a Service

Fraud Detection

AI Guardrails

Captcha

Blockchain as a Service

ID Verification

Managed Security Service

Middleware

Enterprise Distributed Application Service

Microservices Engine

Alibaba Cloud Service Mesh

SchedulerX

ApsaraMQ for RocketMQ

ApsaraMQ for Kafka

ApsaraMQ for RabbitMQ

ApsaraMQ for MQTT

Simple Message Queue (formerly MNS)

CloudFlow

EventBridge

Application Real-Time Monitoring Service

Managed Service for Prometheus

Managed Service for Grafana

Managed Service for OpenTelemetry

Performance Testing

STAROps

Databases

ApsaraDB Console

PolarDB

ApsaraDB RDS

ApsaraDB for OceanBase (Deprecated)

Tair (Redis® OSS-Compatible)

Lindorm

Time Series Database

ApsaraDB for MongoDB

ApsaraDB for HBase

ApsaraDB for Memcache

ApsaraDB for MyBase

AnalyticDB

ApsaraDB for ClickHouse

ApsaraDB for SelectDB

Data Transmission Service

Database Autonomy Service

Data Management

Database Gateway - Deprecated

ApsaraDB for Cassandra - Deprecated

Analytics Computing

MaxCompute

Hologres

Realtime Compute for Apache Flink

Elasticsearch

Vector Retrieval Service for Milvus

E-MapReduce

Data Lake Formation

DataV

Quick BI

Quick Audience

Quick Tracking

DataWorks

DataHub

Dataphin

Media Services

ApsaraVideo VOD

ApsaraVideo Live

Intelligent Media Services

ApsaraVideo Media Processing

Apsara Video SDK

Enterprise Services & Cloud Communication

Energy Expert

CloudQuotation

Salesforce on Alibaba Cloud

GoChina ICP Filing Assistant

Marketplace

Alibaba Mail

Direct Mail

Short Message Service

Voice Service

Phone Number Verification Service

Cell Phone Number Service

Chat App Message Service

Financial Intelligence Engine

Domain Names and Websites

Domain Names

ICP Filing

Alibaba Cloud DNS

End User Computing

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

AgentBay

Internet of Things

IoT Platform

Serverless

Serverless App Engine

CloudFlow

EventBridge

Simple Message Queue (formerly MNS)

Function Compute

Developer Tools

OpenAPI Explorer

Alibaba Cloud SDK

Cloud Shell

Resource Orchestration Service

Alibaba Cloud CLI

BSS OpenAPI

Terraform

Pulumi

Ticket System API

Mobile Platform as a Service

Alibaba Cloud DevOps

API Gateway

Cloud Control API

AI Coding Assistant Lingma

Cloud Skills Portal

Migration & O&M Management

CloudOps Orchestration Service

Cloud Monitor

Intelligent Advisor

Cloud Governance Center

ActionTrail

Cloud Config

Resource Access Management

Resource Management

Cloud Architect Design Tools

Migration Hub

Server Migration Center

Service Catalog

Logic Composer

Quota Center

CloudSSO

HTTPDNS

Solutions

SAP

SuperApp

OpenLake

Membership Service

Expenses and Costs

Account Center

More

Support

Legal

Tech Share Terms and Conditions

After Sales Support

China Gateway Program

Service Level Objectives

Management Console

Security Control

Wan2.7-Image supports text-to-image, text-to-image-set, image-to-image-set, image editing, and multi-image reference generation.

Model overview

ModelDescriptionOutput image specifications
ModelDescriptionOutput image specifications
wan2.7-image-proWan 2.7 image Pro. Supports 4K output for text-to-image generation (not for image sets).Image format: PNG. For image resolution and dimensions, see the size parameter.
wan2.7-imageWan 2.7 image. Faster generation.

Note

Before you call a model, check Model list and prices for regional model availability.

Prerequisites

Obtain an API key and export the API key as an environment variable.

Important

The Beijing and Singapore regions have separate API keys and request endpoints. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors.

HTTP synchronous

Returns the result in a single request. Recommended for most use cases.

Singapore

Beijing

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

When calling, replace WorkspaceId with your actual workspace ID.

POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

#### Request parametersText-to-image Image editing Interactive editing Image set generation > The wan2.7-image-pro model supports 4K resolution for text-to-image generation only. Image editing and image set generation support up to 2K resolution. curl 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": "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 } }' curl 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": "wan2.7-image-pro", "input": { "messages": [ { "role": "user", "content": [ {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"}, {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"}, {"text": "Spray-paint the graffiti from image 2 onto the car in image 1"} ] } ] }, "parameters": { "size": "2K", "n": 1, "watermark": false } }' curl 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": "wan2.7-image-pro", "input": { "messages": [ { "role": "user", "content": [ {"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"}, {"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"}, {"text": "Place the alarm clock from image 1 into the bounding box of image 2, and blend the scene and lighting naturally."} ] } ] }, "parameters": { "bbox_list": [[],[[989, 515, 1138, 681]]], "size": "2K", "n": 1, "watermark": false } }' curl 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": "wan2.7-image-pro", "input": { "messages": [ { "role": "user", "content": [ {"text": "A cinematic group of images documenting the same stray ginger cat. The features must be consistent throughout. First image: In spring, the ginger cat weaves through blooming cherry blossom trees. Second image: In summer, the ginger cat cools off in the shade on an old street. Third image: In autumn, the ginger cat steps on a ground covered with golden fallen leaves. Fourth image: In winter, the ginger cat walks on the snow, leaving footprints."} ] } ] }, "parameters": { "enable_sequential": true, "n": 4, "size": "2K" } }'
##### Headers
Content-Typestring (Required) The content type of the request. Must be application/json.
Authorizationstring (Required) Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
##### Request body
modelstring (Required) The model name. Valid values: wan2.7-image-pro, wan2.7-image.
inputobject (Required) The input object. Properties messagesarray (Required) An array of request content. Only single-turn conversations are supported. Properties rolestring (Required) The message role. Must be user. contentarray (Required) An array of message content. Properties textstring The text prompt. Supports Chinese and English. Maximum 5,000 characters. Each character, letter, number, or symbol counts as one. Excess characters are truncated. imagestring The URL or Base64-encoded string of the input image. Image limits: - Image format: JPEG, JPG, PNG (alpha channels are not supported), BMP, WEBP. - Image resolution: The width and height must be between 240 and 8,000 pixels. The aspect ratio must be between 1:8 and 8:1. - File size: No more than 20 MB. Image number limits: - You can input 0 to 9 images. - When you input multiple images, you must pass multiple image objects in the content array. The order of the objects in the array determines the order of the images. Supported input formats: 1. Use a publicly accessible URL - Supports HTTP or HTTPS protocols. - Example: http://wanx.alicdn.com/material/xxx.jpeg. 2. Pass a Base64-encoded image string - Format: data:{MIME_type};base64,{base64_data} - Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (This is for illustration only. You must pass the complete string.) - For more information, see Image input methods.
parametersobject (Optional) Model parameter settings. Properties bbox_listList[List[List[int]]] (Optional) The bounding box area for interactive editing. - The length of the list must match the number of input images. If an image does not require editing, pass an empty list [] in the corresponding position. - Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y). Use absolute pixel coordinates of the original image. The top-left coordinate is (0, 0). - A single image supports a maximum of two bounding boxes. Example: Input 3 images, where the second image has no bounding box and the first image has two bounding boxes: plaintext [ [[0, 0, 12, 12], [25, 25, 100, 100]], # Image 1 (2 boxes) [], # Image 2 (no box) [[10, 10, 50, 50]] # Image 3 (1 box) ] enable_sequentialboolean (Optional) Controls the image generation mode: - false (default): The default output mode. - true: The image set output mode. sizestring (Optional) The output image resolution. Supports two mutually exclusive methods: Model: wan2.7-image-pro - Method 1: Specify the output image resolution (Recommended) - Supports 1K, 2K (default), and 4K specifications. - Scope of application: - Text-to-image (no image input, not for image set generation): Supports 1K, 2K, and 4K. - Other scenarios: Supports 1K and 2K. - Total pixels for each specification: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096 - Image aspect ratio: - When an image is input: The output aspect ratio matches the input image (the last one if multiple images are input) and is scaled to the selected resolution. - When no image is input: The output is a square image. - Method 2: Specify the width and height in pixels for the generated image - Text-to-image: Total pixels are between 768×768 and 4096×4096. The aspect ratio is between 1:8 and 8:1. - Other scenarios: Total pixels are between 768×768 and 2048×2048. The aspect ratio is between 1:8 and 8:1. Model: wan2.7-image - Method 1: Specify the output image resolution (Recommended) - Supports 1K and 2K (default) specifications. 4K is not supported. - Method 2: Specify the width and height in pixels for the generated image - In all scenarios, the total pixels are between 768×768 and 2048×2048. The aspect ratio is between 1:8 and 8:1. > The pixel values of the output image may have minor differences from the specified values. nint (Optional) Important The n parameter directly affects cost: unit price × number of successfully generated images. Confirm the model pricing before calling. - When image set mode is disabled, this value represents the number of images to generate. The range is 1 to 4. Defaults to 1. - When image set mode is enabled, this value represents the maximum number of images to generate. The range is 1 to 12. Defaults to 12. The actual number is determined by the model and will not exceed n. thinking_modeboolean (Optional) Enables thinking mode. Defaults to true. This parameter is effective only when image set mode is disabled and no image is input. When enabled, the model enhances its inference capabilities to improve output quality, but this increases generation time. color_palettearray (Optional) A custom color theme. An array of objects, each with a hexadecimal color and a ratio. Must include 3 to 10 colors. 8 colors recommended. This is available only when image set mode is disabled (enable_sequential=false). Properties hexstring (Required) The color value in hexadecimal (HEX) format. ratiostring (Required) The percentage of the color. Must be accurate to two decimal places (such as "25.00%"). The sum of all ratio values must be 100.00%. Click to view an input example json "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%" } ] watermarkbool (Optional) Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated". - false (default) - true seedinteger (optional) Random number seed. Valid range: [0,2147483647]. Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed. Note: Image generation is probabilistic. Even with the same seed, results may vary.
#### Response parametersSuccessful task execution Abnormal task execution Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly. json { "output": { "choices": [ { "finish_reason": "stop", "message": { "content": [ { "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx", "type": "image" } ], "role": "assistant" } } ], "finished": true }, "usage": { "image_count": 1, "input_tokens": 10867, "output_tokens": 2, "size": "1488*704", "total_tokens": 10869 }, "request_id": "71dfc3c6-f796-9972-97e4-bc4efc4faxxx" } If a task fails, the code and message fields in the response indicate the error cause. See Error codes. json { "request_id": "a4d78a5f-655f-9639-8437-xxxxxx", "code": "InvalidParameter", "message": "num_images_per_prompt must be 1" }
outputobject Task output information. Properties choicesarray The output content generated by the model. Properties finish_reasonstring The reason the task stopped. stop indicates natural completion. messageobject The message returned by the model. Properties rolestring The message role. Always assistant. contentarray Properties typestring Value: image. imagestring The URL of the generated image. Format: PNG. The link is valid for 24 hours. Download the image promptly. finishedboolean Indicates whether the task is finished. Default: false.
usageobject Usage statistics for the request. Only successful results are counted. Properties image_countinteger The number of generated images. sizestring The resolution of the generated image. Example: 1376*768. input_tokensinteger The number of input tokens (not billed). Billing is based on the number of images. output_tokensinteger The number of output tokens (not billed). Billing is based on the number of images. total_tokensinteger The total number of tokens (not billed). Billing is based on the number of images.
request_idstring Unique request identifier for tracing and troubleshooting.
codestring Error code. Returned only for failed requests. See Error codes.
messagestring Detailed error message. Returned only for failed requests. See Error codes.

HTTP asynchronous

Best for long-running tasks. Submit a task, then poll for status and results.

Step 1: Create a task to get the task ID

Singapore

Beijing

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

When calling, replace WorkspaceId with your actual workspace ID.

POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation

#### Request parametersText-to-image Image editing Interactive editing Image set generation > The wan2.7-image-pro model supports 4K resolution for text-to-image generation only. Image editing and image set generation support up to 2K resolution. curl curl --location 'https://{WorkspaceId}.ap-southeast-1.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 } }' curl curl --location 'https://{WorkspaceId}.ap-southeast-1.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": [ {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"}, {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"}, {"text": "Spray-paint the graffiti from image 2 onto the car in image 1"} ] } ] }, "parameters": { "size": "2K", "n": 1, "watermark": false } }' curl curl --location 'https://{WorkspaceId}.ap-southeast-1.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": [ {"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"}, {"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"}, {"text": "Place the alarm clock from image 1 into the selected area of image 2, and blend the scene and lighting naturally."} ] } ] }, "parameters": { "bbox_list": [[],[[989, 515, 1138, 681]]], "size": "2K", "n": 1, "watermark": false } }' > The wan2.7-image-pro model supports up to 2K resolution for image set generation. curl curl --location 'https://{WorkspaceId}.ap-southeast-1.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 cinematic photo set featuring the same stray orange cat, whose features must remain consistent across all images. First image: In spring, the cat weaves through blooming cherry blossom trees. Second image: In summer, the cat cools off in the shade on an old street. Third image: In autumn, the cat steps on a ground covered in golden fallen leaves. Fourth image: In winter, the cat walks on the snow, leaving footprints."} ] } ] }, "parameters": { "enable_sequential": true, "n": 4, "size": "2K" } }'
##### Headers
Content-Typestring (Required) The content type of the request. Must be application/json.
Authorizationstring (Required) Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
X-DashScope-Asyncstring (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.
##### Request body
modelstring (Required) The model name. Valid values: wan2.7-image-pro, wan2.7-image.
inputobject (Required) The input object. Properties messagesarray (Required) An array of request content. Only single-turn conversations are supported. Properties rolestring (Required) The message role. Must be user. contentarray (Required) An array of message content. Properties textstring The text prompt. Supports Chinese and English. Maximum 5,000 characters. Each character, letter, number, or symbol counts as one. Excess characters are truncated. imagestring The URL or Base64-encoded string of the input image. Image limits: - Image format: JPEG, JPG, PNG (alpha channels are not supported), BMP, WEBP. - Image resolution: The width and height must be between 240 and 8,000 pixels. The aspect ratio must be between 1:8 and 8:1. - File size: No more than 20 MB. Image number limits: - You can input 0 to 9 images. - When you input multiple images, you must pass multiple image objects in the content array. The order of the objects in the array determines the order of the images. Supported input formats: 1. Use a publicly accessible URL - Supports HTTP or HTTPS protocols. - Example: http://wanx.alicdn.com/material/xxx.jpeg. 2. Pass a Base64-encoded image string - Format: data:{MIME_type};base64,{base64_data} - Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (This is for illustration only. You must pass the complete string.) - For more information, see Image input methods.
parametersobject (Optional) Model parameter settings. Properties bbox_listList[List[List[int]]] (Optional) The bounding box area for interactive editing. - The length of the list must match the number of input images. If an image does not require editing, pass an empty list [] in the corresponding position. - Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y). Use absolute pixel coordinates of the original image. The top-left coordinate is (0, 0). - A single image supports a maximum of two bounding boxes. Example: Input 3 images, where the second image has no bounding box and the first image has two bounding boxes: plaintext [ [[0, 0, 12, 12], [25, 25, 100, 100]], # Image 1 (2 boxes) [], # Image 2 (no box) [[10, 10, 50, 50]] # Image 3 (1 box) ] enable_sequentialboolean (Optional) Controls the image generation mode: - false (default): The default output mode. - true: The image set output mode. sizestring (Optional) The output image resolution. Supports two mutually exclusive methods: Model: wan2.7-image-pro - Method 1: Specify the output image resolution (Recommended) - Supports 1K, 2K (default), and 4K specifications. - Scope of application: - Text-to-image (no image input, not for image set generation): Supports 1K, 2K, and 4K. - Other scenarios: Supports 1K and 2K. - Total pixels for each specification: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096 - Image aspect ratio: - When an image is input: The output aspect ratio matches the input image (the last one if multiple images are input) and is scaled to the selected resolution. - When no image is input: The output is a square image. - Method 2: Specify the width and height in pixels for the generated image - Text-to-image: Total pixels are between 768×768 and 4096×4096. The aspect ratio is between 1:8 and 8:1. - Other scenarios: Total pixels are between 768×768 and 2048×2048. The aspect ratio is between 1:8 and 8:1. Model: wan2.7-image - Method 1: Specify the output image resolution (Recommended) - Supports 1K and 2K (default) specifications. 4K is not supported. - Method 2: Specify the width and height in pixels for the generated image - In all scenarios, the total pixels are between 768×768 and 2048×2048. The aspect ratio is between 1:8 and 8:1. > The pixel values of the output image may have minor differences from the specified values. nint (Optional) Important The n parameter directly affects cost: unit price × number of successfully generated images. Confirm the model pricing before calling. - When image set mode is disabled, this value represents the number of images to generate. The range is 1 to 4. Defaults to 1. - When image set mode is enabled, this value represents the maximum number of images to generate. The range is 1 to 12. Defaults to 12. The actual number is determined by the model and will not exceed n. thinking_modeboolean (Optional) Enables thinking mode. Defaults to true. This parameter is effective only when image set mode is disabled and no image is input. When enabled, the model enhances its inference capabilities to improve output quality, but this increases generation time. color_palettearray (Optional) A custom color theme. An array of objects, each with a hexadecimal color and a ratio. Must include 3 to 10 colors. 8 colors recommended. This is available only when image set mode is disabled (enable_sequential=false). Properties hexstring (Required) The color value in hexadecimal (HEX) format. ratiostring (Required) The percentage of the color. Must be accurate to two decimal places (such as "25.00%"). The sum of all ratio values must be 100.00%. Click to view an input example json "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%" } ] watermarkbool (Optional) Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated". - false (default) - true seedinteger (optional) Random number seed. Valid range: [0,2147483647]. Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed. Note: Image generation is probabilistic. Even with the same seed, results may vary.
#### Response parametersSuccessful response Error response Save the task_id to query the task status and result. json { "output": { "task_status": "PENDING", "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx" }, "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx" } Task creation failed. See Error codes. json { "code": "InvalidApiKey", "message": "No API-key provided.", "request_id": "7438d53d-6eb8-4596-8835-xxxxxx" }
outputobject Task output information. Properties task_idstring The task ID. Valid for queries for 24 hours. task_statusstring The status of the task. Enumeration values - PENDING - RUNNING - SUCCEEDED - FAILED - CANCELED - UNKNOWN: The task does not exist or its status is unknown.
request_idstring Unique request identifier for tracing and troubleshooting.
codestring Error code. Returned only for failed requests. See Error codes.
messagestring Detailed error message. Returned only for failed requests. See Error codes.

Step 2: Query the result by task ID

Singapore

Beijing

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

#### Request parametersQuery task result 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 curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \ --header "Authorization: Bearer $DASHSCOPE_API_KEY"
##### Headers
Authorizationstring (Required) Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
##### Path parameters
task_idstring (Required) The ID of the task.
#### Response parametersSuccessful task execution Abnormal task execution Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly. json { "request_id": "810fa5f5-334c-91f3-aaa4-ed89cf0caxxx", "output": { "task_id": "a81ee7cb-014c-473d-b842-76e98311cxxx", "task_status": "SUCCEEDED", "submit_time": "2026-03-26 17:16:01.663", "scheduled_time": "2026-03-26 17:16:01.716", "end_time": "2026-03-26 17:16:22.961", "finished": true, "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx", "type": "image" } ] } } ] }, "usage": { "size": "2976*1408", "total_tokens": 11017, "image_count": 1, "output_tokens": 2, "input_tokens": 11015 } } If a task fails, the code and message fields in the response indicate the error cause. See Error codes. json { "request_id": "a4d78a5f-655f-9639-8437-xxxxxx", "code": "InvalidParameter", "message": "num_images_per_prompt must be 1" }
outputobject Task output information. Properties task_idstring The task ID. Valid for queries for 24 hours. task_statusstring The status of the task. Enumeration values - PENDING - RUNNING - SUCCEEDED - FAILED - CANCELED - UNKNOWN: The task does not exist or its status is unknown. State transitions during polling: - PENDING → RUNNING → SUCCEEDED or FAILED. - The initial query status is usually PENDING or RUNNING. - When the status changes to SUCCEEDED, the response contains the generated image URL. - If the status is FAILED, check the error message and retry the task. submit_timestring The time when the task was submitted. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS. scheduled_timestring The time when the task was executed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS. end_timestring The time when the task was completed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS. finishedboolean Indicates whether the task is finished. Default: false. choicesarray The output content generated by the model. Properties finish_reasonstring The reason the task stopped. stop indicates natural completion. messageobject The message returned by the model. Properties rolestring The message role. Always assistant. contentarray Properties typestring Values: text, image. textstring The generated text. imagestring The URL of the generated image. Format: PNG. The link is valid for 24 hours. Download the image promptly.
usageobject Usage statistics for the request. Only successful results are counted. Properties image_countinteger The number of generated images. sizestring The resolution of the generated image. Example: 1376*768. input_tokensinteger The number of input tokens (not billed). Billing is based on the number of images. output_tokensinteger The number of output tokens (not billed). Billing is based on the number of images. total_tokensinteger The total number of tokens (not billed). Billing is based on the number of images.
request_idstring Unique request identifier for tracing and troubleshooting.
codestring Error code. Returned only for failed requests. See Error codes.
messagestring Detailed error message. Returned only for failed requests. See Error codes.

Python SDK

SDK parameter names are largely consistent with the HTTP API.

Image generation tasks can take time, so the SDK wraps the HTTP asynchronous workflow. Both synchronous and asynchronous calls are supported.

Task duration depends on queue length and service status.

Important

Make sure your DashScope Python SDK version is 1.25.15 or later. To update, see Install SDK.

Both base_url and API key are region-specific. The following example uses the Singapore region:

Singapore

Beijing

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When calling, replace WorkspaceId with your actual workspace ID.

https://dashscope.aliyuncs.com/api/v1

Image editing

Synchronous call

Asynchronous call

Request example
python
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# The following is the base_url for the Singapore region. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 encoding function ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Unsupported or unrecognized image format")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
Image input methods:
The following are three methods for image input. You need to choose only one.
1. Use a public URL: This method is suitable for publicly accessible images.
2. Use a local file: This method is suitable for local development and testing.
3. Use Base64 encoding: This method is suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

message = Message(
    role="user",
    content=[\
        {"text": "Spray the graffiti from image 2 onto the car in image 1"},\
        {"image": image_1},\
        {"image": image_2},\
    ],
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
    model="wan2.7-image-pro",
    api_key=api_key,
    messages=[message],
    watermark=False,
    n=1,
    size="2K",  # wan2.7-image-pro supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
)

# Extract the result image URL and save the image to a local file.
if rsp.status_code == 200:
    for i, choice in enumerate(rsp.output.choices):
        for j, content in enumerate(choice["message"]["content"]):
            if content.get("type") == "image":
                image_url = content["image"]
                file_name = f"output_{i}_{j}.png"
                # The result URL is valid for 24 hours. Please download it promptly.
                urllib.request.urlretrieve(image_url, file_name)
                print(f"Image saved to {file_name}")
else:
    print(f"Failed: status_code={rsp.status_code}, message={rsp.message}")
Response example

The URL is valid for 24 hours. Download the image promptly.

json
{
    "status_code": 200,
    "request_id": "81d868c6-6ce1-92d8-a90d-d2ee71xxxxxx",
    "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,
        "finished": true
    },
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "characters": 0,
        "image_count": 1,
        "size": "2985*1405",
        "total_tokens": 18792
    }
}
Request example
python
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus

# The following is the base_url for the Singapore region. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 encoding function ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Unsupported or unrecognized image format.")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
Image input methods:
Three image input methods are provided below. Choose one.
1. Use a public URL - suitable for publicly accessible images.
2. Use a local file - suitable for local development and testing.
3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

# Create an asynchronous task.
def create_async_task():
    print("Creating async task...")
    message = Message(
        role="user",
        content=[\
            {"text": "Spray the graffiti from image 2 onto the car in image 1."},\
            {"image": image_1},\
            {"image": image_2},\
        ],
    )
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        watermark=False,
        n=1,
        size="2K",  # wan2.7-image-pro supports 4K resolution only for text-to-image generation scenarios. Image editing and collage generation support a maximum resolution of 2K.
    )

    if response.status_code == 200:
        print("Task created successfully:", response)
        return response
    else:
        raise Exception(f"Failed to create task: {response.code} - {response.message}")

# Wait for the task to complete.
def wait_for_completion(task_response):
    print("Waiting for task completion...")
    status = ImageGeneration.wait(task=task_response, api_key=api_key)

    if status.output.task_status == "SUCCEEDED":
        print("Task succeeded!")
        # Extract the result image URL and save the image to a local file.
        for i, choice in enumerate(status.output.choices):
            for j, content in enumerate(choice["message"]["content"]):
                if content.get("type") == "image":
                    image_url = content["image"]
                    file_name = f"output_{i}_{j}.png"
                    # The result URL is valid for 24 hours. Download the image in a timely manner.
                    urllib.request.urlretrieve(image_url, file_name)
                    print(f"Image saved to {file_name}")
    else:
        raise Exception(f"Task failed with status: {status.output.task_status}")

# Obtain information about the asynchronous task.
def fetch_task_status(task):
    print("Fetching task status...")
    status = ImageGeneration.fetch(task=task, api_key=api_key)

    if status.status_code == HTTPStatus.OK:
        print("Task status:", status.output.task_status)
        print("Response details:", status)
    else:
        print(f"Failed to fetch status: {status.code} - {status.message}")

# Cancel the asynchronous task.
def cancel_task(task):
    print("Canceling task...")
    response = ImageGeneration.cancel(task=task, api_key=api_key)

    if response.status_code == HTTPStatus.OK:
        print("Task canceled successfully:", response.output.task_status)
    else:
        print(f"Failed to cancel task: {response.code} - {response.message}")

# Main execution flow.
if __name__ == "__main__":
    task = create_async_task()
    wait_for_completion(task)
Response example
  1. Response example for creating a task
json
{
       "status_code": 200,
       "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
       "code": "",
       "message": "",
       "output": {
           "text": null,
           "finish_reason": null,
           "choices": null,
           "audio": null,
           "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
           "task_status": "PENDING"
       },
       "usage": {
           "input_tokens": 0,
           "output_tokens": 0,
           "characters": 0
       }
}
  1. Response example for querying a task result

The URL is valid for 24 hours. Download the image promptly.

json
{
       "status_code": 200,
       "request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx",
       "code": null,
       "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": "127ec645-118f-4884-955d-0eba8dxxxxxx",
           "task_status": "SUCCEEDED",
           "submit_time": "2026-03-31 22:58:47.646",
           "scheduled_time": "2026-03-31 22:58:47.683",
           "end_time": "2026-03-31 22:58:59.642",
           "finished": true
       },
       "usage": {
           "input_tokens": 18711,
           "output_tokens": 2,
           "characters": 0,
           "size": "2985*1405",
           "total_tokens": 18713,
           "image_count": 1
       }
}

Image set generation

Synchronous call

Asynchronous call

Request example
python
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# The following is the base_url for the Singapore region. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 encoding function ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Unsupported or unrecognized image format")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
Description of image input methods (for image-to-image sequence generation):
Choose one of the following three image input methods:
1. Use a public URL - Suitable for publicly accessible images.
2. Use a local file - Suitable for local development and testing.
3. Use Base64 encoding - Suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [Method 2] Use a local file (supports both absolute and relative paths)
# image_1 = "file:///path/to/your/image.png"

# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/image.png")

message = Message(
    role="user",
    content=[\
        {\
            "text": "A cinematic image sequence featuring the same stray orange cat, whose features must be consistent across all images. First image: In spring, the orange cat weaves through blooming cherry blossom trees. Second image: In summer, the orange cat cools off in the shade of a tree on an old street. Third image: In autumn, the orange cat walks on a carpet of golden fallen leaves. Fourth image: In winter, the orange cat leaves footprints as it walks on the snow."\
        }\
        # For image-to-image sequence generation: Uncomment the following lines and comment out the plain text above.\
        # {"text": "Generate a four-seasons image sequence based on the style of the reference image"},\
        # {"image": image_1}\
    ],
)

print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
    model="wan2.7-image-pro",
    api_key=api_key,
    messages=[message],
    enable_sequential=True,
    n=4,
    size="2K",  # wan2.7-image-pro supports 4K resolution only in text-to-image scenarios. Image editing and image sequence generation support a maximum resolution of 2K.
)

# Extract the resulting image URLs and save the images locally.
if rsp.status_code == 200:
    for i, choice in enumerate(rsp.output.choices):
        for j, content in enumerate(choice["message"]["content"]):
            if content.get("type") == "image":
                image_url = content["image"]
                file_name = f"output_{i}_{j}.png"
                # The result URL is valid for 24 hours. Download the image promptly.
                urllib.request.urlretrieve(image_url, file_name)
                print(f"Image saved to {file_name}")
else:
    print(f"Failed: status_code={rsp.status_code}, message={rsp.message}")
Response example

The URL is valid for 24 hours. Download the image promptly.

json
{
    "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"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        }\
                    ]\
                }\
            }\
        ],
        "audio": null,
        "finished": true
    },
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "characters": 0,
        "image_count": 4,
        "size": "2048*2048",
        "total_tokens": 731
    }
}
Request example
python
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# The following base_url is for the Singapore region. The base_url varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# If you have not configured the DASHSCOPE_API_KEY environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 encoding function ---
# The Base64 data URI scheme is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Unsupported or unrecognized image format")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
Description of image input methods (for image-to-image sequence generation):
The following three image input methods are provided. Choose one of them.
1. Use a public URL: Suitable for images that are publicly accessible.
2. Use a local file: Suitable for local development and testing.
3. Use Base64 encoding: Suitable for private images or scenarios that require encrypted transmission.
"""
# [Method 1] Use a public image URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [Method 2] Use a local file (absolute and relative paths are supported)
# image_1 = "file:///path/to/your/image.png"

# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/image.png")

def main():
    message = Message(
        role="user",
        content=[\
            {\
                "text": "A cinematic sequence of images documenting the same stray orange cat, whose features must remain consistent across all images. Image 1: In spring, the cat weaves through blooming cherry blossom trees. Image 2: In summer, the cat cools off in the shade of trees on an old street. Image 3: In autumn, the cat steps on a carpet of golden fallen leaves. Image 4: In winter, the cat walks on the snow, leaving footprints."\
            }\
            # Image-to-image sequence generation scenario: Uncomment the following lines and comment out the plain text above.\
            # {"text": "Generate a sequence of four seasonal images based on the style of the reference image."},\
            # {"image": image_1}\
        ],
    )

    # Submit an asynchronous task
    print("Submitting an asynchronous task...")
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        enable_sequential=True,
        n=4,
        size="2K",  # wan2.7-image-pro supports 4K resolution only in text-to-image scenarios. Image editing and image sequence generation support a maximum resolution of 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!")
            # Extract the result image URLs and save them to a local device.
            for i, choice in enumerate(status.output.choices):
                for j, content in enumerate(choice["message"]["content"]):
                    if content.get("type") == "image":
                        image_url = content["image"]
                        file_name = f"output_{i}_{j}.png"
                        # The result URLs are valid for 24 hours. Download the images in a timely manner.
                        urllib.request.urlretrieve(image_url, file_name)
                        print(f"Image saved to {file_name}")
        else:
            print(f"Task failed. Status: {status.output.task_status}")
    else:
        print(f"Failed to create the task: {response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {e}")
Response example
  1. Response example for creating a task
json
{
       "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
       }
}
  1. Response example for querying a task result

The URL is valid for 24 hours. Download the image promptly.

json
{
       "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"\
                           },\
                           {\
                               "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                               "type": "image"\
                           },\
                           {\
                               "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                               "type": "image"\
                           },\
                           {\
                               "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": 4
       }
}

Java SDK

SDK parameter names are largely consistent with the HTTP API.

Image generation tasks can take time, so the SDK wraps the HTTP asynchronous workflow. Both synchronous and asynchronous calls are supported.

Important

Make sure your DashScope Java SDK version is 2.22.13 or later.

Singapore

Beijing

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When calling, replace WorkspaceId with your actual workspace ID.

https://dashscope.aliyuncs.com/api/v1

Image editing

Synchronous call

Asynchronous call

Request example
java
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro Image Editing - Synchronous Call Example
 */
public class Main {

    static {
        // The following is the URL for the Singapore region. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 encoding function ---
    // Base64 encoding format: data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * Description of image input methods:
         * Three image input methods are provided below. Select one.
         * 1. Use a public URL: Suitable for publicly accessible images.
         * 2. Use a local file: Suitable for local development and testing.
         * 3. Use Base64 encoding: Suitable for private images or scenarios that require encrypted transmission.
         */
        // Method 1: Use a public image URL.
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // Method 2: Use a local file. Both absolute and relative paths are supported.
        // Format: file:// + file path
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // Method 3: Use a Base64-encoded image.
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // Build a multi-image input message.
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // Multi-image input is supported. You can provide multiple reference images.
                        Collections.singletonMap("text", "Spray the graffiti from image 2 onto the car in image 1"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .n(1)
                .size("2K") // For wan2.7-image-pro, only the text-to-image generation scenario supports 4K resolution. Image editing and collage generation support a maximum resolution of 2K.
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---sync call for image editing, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        // Extract the result image URL and save it to a local file.
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Response example

The URL is valid for 24 hours. Save it promptly.

java
{
    "requestId": "1bf6173a-e8de-9f75-94d3-5e618f875xxx",
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "total_tokens": 18792,
        "image_count": 1,
        "size": "2985*1405"
    },
    "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"\
                        }\
                    ]\
                }\
            }\
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
Request example
java
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro Image Editing - Asynchronous Invocation Example
 */
public class Main {

    static {
        // The following URL is for the Singapore region. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // The API key varies by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 encoding function ---
    // The Base64 encoding format is data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * Description of image input methods:
         * The following three image input methods are provided. You can choose one of them.
         * 1. Use a public URL - Suitable for publicly accessible images.
         * 2. Use a local file - Suitable for local development and testing.
         * 3. Use Base64 encoding - Suitable for scenarios that involve private images or require encrypted transmission.
         */
        // [Method 1] Use a public image URL
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // [Method 2] Use a local file (supports absolute and relative paths)
        // Required format: file:// + file path
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // [Method 3] Use a Base64-encoded image
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // Build a multi-image input message
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // Supports multi-image input. You can provide multiple reference images.
                        Collections.singletonMap("text", "Spray-paint the graffiti from image 2 onto the car in image 1"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .n(1)
                .size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. For image editing and composite image generation, the maximum supported resolution is 2K.
                .messages(Arrays.asList(message))
                .build();

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

        String taskId = result.getOutput().getTaskId();
        // Wait for the task to complete
        waitTask(taskId);
    }

    public static void waitTask(String taskId) throws ApiException, NoApiKeyException, IOException {
        ImageGeneration imageGeneration = new ImageGeneration();
        System.out.println("\n---waiting for task completion----");
        ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
        // Fetch the resulting image URL and save it to a local file
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Response example
  1. Response example for creating a task
json
{
       "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
       "output": {
           "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
           "task_status": "PENDING"
       },
       "status_code": 200,
       "code": "",
       "message": ""
}
  1. Response example for querying a task result

The URL is valid for 24 hours. Save it promptly.

json
{
       "requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx",
       "usage": {
           "input_tokens": 18711,
           "output_tokens": 2,
           "total_tokens": 18713,
           "image_count": 1,
           "size": "2985*1405"
       },
       "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": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
           "task_status": "SUCCEEDED",
           "finished": true,
           "submit_time": "2026-03-31 19:57:58.840",
           "scheduled_time": "2026-03-31 19:57:58.877",
           "end_time": "2026-03-31 19:58:11.563"
       },
       "status_code": 200,
       "code": "",
       "message": ""
}

Image set generation

Synchronous call

Asynchronous call

Request example
java
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * An example of using wan2.7-image-pro for image series generation through synchronous calls in the Singapore region.
 */
public class Main {

    static {
        // The following URL is for the Singapore region. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

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

    // --- Base64 encoding function ---
    // The format for Base64 encoding is data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * Image input methods (for image-to-image series generation):
         * Three image input methods are provided below. Choose one.
         * 1. Public URL: Suitable for images that are already publicly accessible.
         * 2. Local file: Suitable for local development and testing.
         * 3. Base64 encoding: Suitable for private images or scenarios that require encrypted transmission.
         */
        // Method 1: Use a public image URL
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // Method 2: Use a local file (supports both absolute and relative paths)
        // Format: file:// + file path
        // String image1 = "file:///path/to/your/image.png";

        // Method 3: Use a Base64-encoded image
        // String image1 = encodeFile("/path/to/your/image.png");

        // Build the text input message. This supports both text-to-image and image-to-image series generation. This example demonstrates text-to-image series generation.
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "A cinematic image series documenting the same stray orange cat, whose features must remain consistent. First image: In spring, the cat weaves through blooming cherry blossom trees. Second image: In summer, the cat cools off in the shade on an old street. Third image: In autumn, the cat walks on a carpet of golden fallen leaves. Fourth image: In winter, the cat leaves footprints in the snow.")
                )).build();
        // For image-to-image series generation, uncomment the following code and comment out the plain text message builder above.
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "Generate a four-season image series based on the style of the reference image."),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. Image editing and image series generation support a maximum resolution of 2K.
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("----sync call, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        // Extract the resulting image URLs and save them to a local directory.
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // The resulting URL is valid for 24 hours. Be sure to download it promptly.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Response example

The URL is valid for 24 hours. Save it promptly.

java
{
    "requestId": "4678c314-b37a-91c9-a2ae-2d3cd54bbxxx",
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "total_tokens": 731,
        "image_count": 4,
        "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"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        },\
                        {\
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                            "type": "image"\
                        }\
                    ]\
                }\
            }\
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
Request example
java
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.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro Image Set Generation - Asynchronous Invocation Example (Singapore Region)
 */
public class Main {

    static {
        // The following URL is for the Singapore region. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured environment variables, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // The API key varies by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 encoding function ---
    // The Base64 encoding format is data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    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, IOException {
        /*
         * Description of image input methods (for image-to-image set generation scenarios):
         * The following three image input methods are provided. You can choose one of them.
         * 1. Use a public URL - suitable for publicly accessible images.
         * 2. Use a local file - suitable for local development and testing.
         * 3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
         */
        // [Method 1] Use a public image URL
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // [Method 2] Use a local file (supports absolute and relative paths)
        // Format: file:// + file path
        // String image1 = "file:///path/to/your/image.png";

        // [Method 3] Use a Base64-encoded image
        // String image1 = encodeFile("/path/to/your/image.png");

        // Build the text input message (supports text-to-image set and image-to-image set generation. This example uses text-to-image set generation.)
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "A cinematic image set documenting the same stray orange cat. Its features must be consistent across all images. Image 1: In spring, the orange cat weaves through blooming cherry blossom trees. Image 2: In summer, the orange cat cools off in the shade of a tree on an old street. Image 3: In autumn, the orange cat steps on a carpet of golden fallen leaves. Image 4: In winter, the orange cat leaves footprints as it walks on the snow.")
                )).build();
        // For image-to-image set generation scenarios: uncomment the following code and comment out the plain text construction above.
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "Generate an image set of the four seasons based on the style of the reference image."),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .size("2K") // The wan2.7-image-pro model supports 4K resolution only for text-to-image generation. Image editing and image set generation support a maximum resolution of 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);
        // Fetch the resulting image URLs and save them to a local directory.
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Response example
  1. Response example for creating a task
json
{
       "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx",
       "output": {
           "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
           "task_status": "PENDING"
       },
       "status_code": 200,
       "code": "",
       "message": ""
}
  1. Response example for querying a task result

The URL is valid for 24 hours. Save it promptly.

json
{
       "requestId": "daea7295-4ce0-928a-9a11-4d2bea058xxx",
       "usage": {
           "input_tokens": 720,
           "output_tokens": 11,
           "total_tokens": 731,
           "image_count": 4,
           "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"\
                           },\
                           {\
                               "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                               "type": "image"\
                           },\
                           {\
                               "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",\
                               "type": "image"\
                           },\
                           {\
                               "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": ""
}

Billing and rate limiting

  • For the model's free quota and unit price, see Model pricing.

  • For model rate limiting, see Wanx.

  • Billing details: You are billed based on the number of images successfully generated. Failed calls and processing errors do not incur charges or consume your free quota for new users.

Error codes

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

Previous: Wan text-to-image V2 API referenceNext: Wan2.6 - image generation and editing

Is this page helpful?

Model overview

Prerequisites

HTTP synchronous

HTTP asynchronous

Step 1: Create a task to get the task ID

Step 2: Query the result by task ID

Python SDK

Image editing

Image set generation

Java SDK

Image editing

Image set generation

Billing and rate limiting

Error codes

Contact Us

Sales Support

Live-chat with our sales team or get in touch with a business development professional in your region.

Contact Sales

Technical Support

Open a ticket and get quick help from our technical team.

Open a Ticket >

Connect & Report Abuse

We look forward to your suggestion.

Post a Suggestion > Report Abuse >

\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.

Why Alibaba Cloud

About Alibaba Cloud

Asia Accelerator

Our Global Network

Global Offices

Trust Center

Case Studies

Analyst Reports

Products & Pricings

Pricing Calculator

ECS

SAS

Model Studio

Database

Security

SMS

Solutions

Financial Services

Retail Services

Media Services

Gaming Services

ISV Solutions

Engage

Developer Community

Partner Network

Startups

Marketplace

Join Alibaba Cloud

Resources & Support

Developer Learning Hub

Documentation Center

Training & Certification

Service Notices

Submit a Ticket

Security Report

Qwen Cloud

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links