All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan2.7 - pembuatan dan pengeditan gambar

Last Updated:Jun 30, 2026

Wan2.7-Image mendukung teks-ke-gambar, teks-ke-set-gambar, gambar-ke-set-gambar, pengeditan gambar, dan pembuatan referensi multi-gambar.

Ikhtisar model

Model

Deskripsi

Spesifikasi gambar output

wan2.7-image-pro

Wan 2.7 image Pro. Mendukung output 4K untuk pembuatan teks-ke-gambar (tidak berlaku untuk set gambar).

Format gambar: PNG.

Untuk resolusi dan dimensi gambar, lihat parameter size.

wan2.7-image

Wan 2.7 image. Pembuatan lebih cepat.

Catatan

Sebelum memanggil model, periksa Daftar model dan harga untuk ketersediaan model di wilayah tertentu.

Prasyarat

Dapatkan Kunci API dan ekspor Kunci API sebagai Variabel lingkungan.

Penting

Wilayah China (Beijing) dan Singapura memiliki Kunci API dan titik akhir permintaan yang terpisah. Keduanya tidak dapat saling dipertukarkan. Pemanggilan lintas-wilayah menyebabkan kegagalan otentikasi atau error layanan.

HTTP sinkron

Mengembalikan hasil dalam satu permintaan. Direkomendasikan untuk sebagian besar kasus penggunaan.

Singapura

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Parameter permintaan

Teks-ke-gambar

Model wan2.7-image-pro hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan set gambar mendukung resolusi hingga 2K.
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
        }
    }'
    

Pengeditan gambar

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
        }
    }'
    

Pengeditan interaktif

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
        }
    }'
    

Pembuatan set gambar

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"
        }
    }'
    

Header

Content-Type string (Wajib)

Tipe konten dari permintaan. Harus application/json.

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

Body permintaan

model string (Wajib)

Nama model. Nilai yang valid: wan2.7-image-pro, wan2.7-image.

input object (Wajib)

Objek input.

Properti

messages array (Wajib)

Array konten permintaan. Hanya percakapan satu putaran yang didukung.

Properti

role string (Wajib)

Peran pesan. Harus user.

content array (Wajib)

Array konten pesan.

Properti

text string

Prompt teks. Mendukung bahasa Mandarin dan Inggris. Maksimal 5.000 karakter. Setiap karakter, huruf, angka, atau simbol dihitung sebagai satu. Karakter berlebih akan dipotong.

image string

URL atau string Base64-encoded dari gambar input.

Batasan gambar:

  • Format gambar: JPEG, JPG, PNG (saluran alfa tidak didukung), BMP, WEBP.

  • Resolusi gambar: Lebar dan tinggi harus antara 240 hingga 8.000 piksel. Rasio aspek harus antara 1:8 hingga 8:1.

  • Ukuran file: Tidak lebih dari 20 MB.

Batasan jumlah gambar:

  • Anda dapat menginput 0 hingga 9 gambar.

  • Saat menginput beberapa gambar, Anda harus meneruskan beberapa objek image dalam array content. Urutan objek dalam array menentukan urutan gambar.

Format input yang didukung:

  1. Gunakan URL yang dapat diakses publik

    • Mendukung protokol HTTP atau HTTPS.

    • Contoh: http://wanx.alicdn.com/material/xxx.jpeg.

  2. Teruskan string gambar Base64-encoded

    • Format: data:{MIME_type};base64,{base64_data}

    • Contoh: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (Ini hanya ilustrasi. Anda harus meneruskan string lengkap.)

    • Untuk informasi lebih lanjut, lihat Metode input gambar.

parameters object (Opsional)

Pengaturan parameter model.

Properti

bbox_list List[List[List[int]]] (Opsional)

Area Kotak pembatas untuk pengeditan interaktif.

  • Panjang daftar harus sesuai dengan jumlah gambar input. Jika suatu gambar tidak memerlukan pengeditan, teruskan daftar kosong [] pada posisi yang sesuai.

  • Format koordinat: [x1, y1, x2, y2] (x kiri atas, y kiri atas, x kanan bawah, y kanan bawah). Gunakan koordinat piksel absolut dari gambar asli. Koordinat kiri atas adalah (0, 0).

  • Satu gambar mendukung maksimal dua Kotak pembatas.

Contoh: Input 3 gambar, di mana gambar kedua tidak memiliki Kotak pembatas dan gambar pertama memiliki dua Kotak pembatas:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # Gambar 1 (2 kotak)
  [],                                    # Gambar 2 (tanpa kotak)
  [[10, 10, 50, 50]]                     # Gambar 3 (1 kotak)
]

enable_sequential boolean (Opsional)

Mengontrol mode pembuatan gambar:

  • false (default): Mode output default.

  • true: Mode output set gambar.

size string (Opsional)

Resolusi gambar output. Mendukung dua metode yang saling eksklusif:

Model: wan2.7-image-pro

  • Metode 1: Tentukan resolusi gambar output (Direkomendasikan)

    • Mendukung spesifikasi 1K, 2K (default), dan 4K.

    • Lingkup penerapan:

      • Teks-ke-gambar (tanpa input gambar, bukan untuk pembuatan set gambar): Mendukung 1K, 2K, dan 4K.

      • Skenario lainnya: Mendukung 1K dan 2K.

    • Total piksel untuk setiap spesifikasi: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096

    • Rasio aspek gambar:

      • Saat gambar diinput: Rasio aspek output sesuai dengan gambar input (yang terakhir jika beberapa gambar diinput) dan diskalakan ke resolusi yang dipilih.

      • Saat tidak ada gambar yang diinput: Output berupa gambar persegi.

  • Metode 2: Tentukan lebar dan tinggi dalam piksel untuk gambar yang dihasilkan

    • Teks-ke-gambar: Total piksel antara 768×768 hingga 4096×4096. Rasio aspek antara 1:8 hingga 8:1.

    • Skenario lainnya: Total piksel antara 768×768 hingga 2048×2048. Rasio aspek antara 1:8 hingga 8:1.

Model: wan2.7-image

  • Metode 1: Tentukan resolusi gambar output (Direkomendasikan)

    • Mendukung spesifikasi 1K dan 2K (default). 4K tidak didukung.

  • Metode 2: Tentukan lebar dan tinggi dalam piksel untuk gambar yang dihasilkan

    • Dalam semua skenario, total piksel antara 768×768 hingga 2048×2048. Rasio aspek antara 1:8 hingga 8:1.

Nilai piksel gambar output mungkin memiliki sedikit perbedaan dari nilai yang ditentukan.

n int (Opsional)

Penting

Parameter n secara langsung memengaruhi biaya: harga satuan × jumlah gambar yang berhasil dibuat. Konfirmasi harga model sebelum memanggil.

  • Saat mode set gambar dinonaktifkan, nilai ini merepresentasikan jumlah gambar yang akan dibuat. Rentangnya 1 hingga 4. Default 1.

  • Saat mode set gambar diaktifkan, nilai ini merepresentasikan jumlah maksimum gambar yang akan dibuat. Rentangnya 1 hingga 12. Default 12. Jumlah aktual ditentukan oleh model dan tidak akan melebihi n.

thinking_mode boolean (Opsional)

Mengaktifkan mode thinking. Default true. Parameter ini hanya berlaku saat mode set gambar dinonaktifkan dan tidak ada input gambar. Saat diaktifkan, model meningkatkan kemampuan Inferensinya untuk meningkatkan kualitas output, tetapi ini meningkatkan waktu pembuatan.

color_palette array (Opsional)

Tema warna kustom. Array objek, masing-masing dengan warna heksadesimal dan rasio. Harus mencakup 3 hingga 10 warna. Disarankan 8 warna.

Ini tersedia hanya saat mode set gambar dinonaktifkan (enable_sequential=false).

Properti

hex string (Wajib)

Nilai warna dalam format heksadesimal (HEX).

ratio string (Wajib)

Persentase warna. Harus akurat hingga dua tempat desimal (seperti "25.00%"). Jumlah semua nilai rasio harus 100.00%.

Klik untuk melihat contoh input

"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%"
    }
]

watermark bool (Opsional)

Menambahkan label Watermark di pojok kanan bawah gambar dengan teks tetap "AI Generated".

  • false (default)

  • true

seed integer (opsional)

Bibit angka acak. Rentang valid: [0,2147483647].

Menggunakan seed yang sama menghasilkan output serupa. Jika dihilangkan, algoritma menggunakan seed acak.

Catatan: Pembuatan gambar bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya mungkin berbeda.

Parameter respons

Eksekusi tugas berhasil

Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan.

{
    "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"
}

Eksekusi tugas abnormal

Jika tugas gagal, bidang code dan message dalam respons menunjukkan penyebab error. Lihat 错误码.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Informasi output tugas.

Properti

choices array

Konten output yang dihasilkan oleh model.

Properti

finish_reason string

Alasan tugas berhenti. stop menunjukkan penyelesaian alami.

message object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pesan. Selalu assistant.

content array

Properti

type string

Nilai: image.

image string

URL gambar yang dihasilkan. Format: PNG.

Tautan berlaku selama 24 jam. Segera unduh gambar.

finished boolean

Menunjukkan apakah tugas telah selesai. Default: false.

usage object

Statistik penggunaan untuk permintaan. Hanya hasil yang berhasil yang dihitung.

Properti

image_count integer

Jumlah gambar yang dihasilkan.

size string

Resolusi gambar yang dihasilkan. Contoh: 1376*768.

input_tokens integer

Jumlah token input (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

output_tokens integer

Jumlah token output (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

total_tokens integer

Jumlah total token (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

request_id string

Pengidentifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan error detail. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

HTTP asinkron

Paling cocok untuk tugas berdurasi panjang. Kirim tugas, lalu polling status dan hasilnya.

Langkah 1: Buat tugas untuk mendapatkan ID tugas

Singapura

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Beijing

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Parameter permintaan

Teks-ke-gambar

Model wan2.7-image-pro hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan set gambar mendukung resolusi hingga 2K.
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
        }
    }'
    

Pengeditan gambar

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
        }
    }'
    

Pengeditan interaktif

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
        }
    }'
    

Pembuatan set gambar

Model wan2.7-image-pro mendukung resolusi hingga 2K untuk pembuatan set gambar.
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"
        }
    }'
    

Header

Content-Type string (Wajib)

Tipe konten dari permintaan. Harus application/json.

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

X-DashScope-Async string (Wajib)

Mengaktifkan pemrosesan asinkron. Permintaan HTTP hanya mendukung pemanggilan asinkron. Harus enable.

Penting

Jika header permintaan ini tidak ada, error "current user api does not support synchronous calls" dikembalikan.

Body permintaan

model string (Wajib)

Nama model. Nilai yang valid: wan2.7-image-pro, wan2.7-image.

input object (Wajib)

Objek input.

Properti

messages array (Wajib)

Array konten permintaan. Hanya percakapan satu putaran yang didukung.

Properti

role string (Wajib)

Peran pesan. Harus user.

content array (Wajib)

Array konten pesan.

Properti

text string

Prompt teks. Mendukung bahasa Mandarin dan Inggris. Maksimal 5.000 karakter. Setiap karakter, huruf, angka, atau simbol dihitung sebagai satu. Karakter berlebih akan dipotong.

image string

URL atau string Base64-encoded dari gambar input.

Batasan gambar:

  • Format gambar: JPEG, JPG, PNG (saluran alfa tidak didukung), BMP, WEBP.

  • Resolusi gambar: Lebar dan tinggi harus antara 240 hingga 8.000 piksel. Rasio aspek harus antara 1:8 hingga 8:1.

  • Ukuran file: Tidak lebih dari 20 MB.

Batasan jumlah gambar:

  • Anda dapat menginput 0 hingga 9 gambar.

  • Saat menginput beberapa gambar, Anda harus meneruskan beberapa objek image dalam array content. Urutan objek dalam array menentukan urutan gambar.

Format input yang didukung:

  1. Gunakan URL yang dapat diakses publik

    • Mendukung protokol HTTP atau HTTPS.

    • Contoh: http://wanx.alicdn.com/material/xxx.jpeg.

  2. Teruskan string gambar Base64-encoded

    • Format: data:{MIME_type};base64,{base64_data}

    • Contoh: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (Ini hanya ilustrasi. Anda harus meneruskan string lengkap.)

    • Untuk informasi lebih lanjut, lihat Metode input gambar.

parameters object (Opsional)

Pengaturan parameter model.

Properti

bbox_list List[List[List[int]]] (Opsional)

Area Kotak pembatas untuk pengeditan interaktif.

  • Panjang daftar harus sesuai dengan jumlah gambar input. Jika suatu gambar tidak memerlukan pengeditan, teruskan daftar kosong [] pada posisi yang sesuai.

  • Format koordinat: [x1, y1, x2, y2] (x kiri atas, y kiri atas, x kanan bawah, y kanan bawah). Gunakan koordinat piksel absolut dari gambar asli. Koordinat kiri atas adalah (0, 0).

  • Satu gambar mendukung maksimal dua Kotak pembatas.

Contoh: Input 3 gambar, di mana gambar kedua tidak memiliki Kotak pembatas dan gambar pertama memiliki dua Kotak pembatas:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # Gambar 1 (2 kotak)
  [],                                    # Gambar 2 (tanpa kotak)
  [[10, 10, 50, 50]]                     # Gambar 3 (1 kotak)
]

enable_sequential boolean (Opsional)

Mengontrol mode pembuatan gambar:

  • false (default): Mode output default.

  • true: Mode output set gambar.

size string (Opsional)

Resolusi gambar output. Mendukung dua metode yang saling eksklusif:

Model: wan2.7-image-pro

  • Metode 1: Tentukan resolusi gambar output (Direkomendasikan)

    • Mendukung 1K, 2K (default), dan 4K spesifikasi.

    • Lingkup penerapan:

      • Teks-ke-gambar (tanpa input gambar, bukan untuk pembuatan set gambar): Mendukung 1K, 2K, dan 4K.

      • Skenario lainnya: Mendukung 1K dan 2K.

    • Total piksel untuk setiap spesifikasi: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096

    • Rasio aspek gambar:

      • Saat gambar diinput: Rasio aspek output sesuai dengan gambar input (yang terakhir jika beberapa gambar diinput) dan diskalakan ke resolusi yang dipilih.

      • Saat tidak ada gambar yang diinput: Output berupa gambar persegi.

  • Metode 2: Tentukan lebar dan tinggi dalam piksel untuk gambar yang dihasilkan

    • Teks-ke-gambar: Total piksel antara 768×768 hingga 4096×4096. Rasio aspek antara 1:8 hingga 8:1.

    • Skenario lainnya: Total piksel antara 768×768 hingga 2048×2048. Rasio aspek antara 1:8 hingga 8:1.

Model: wan2.7-image

  • Metode 1: Tentukan resolusi gambar output (Direkomendasikan)

    • Mendukung spesifikasi 1K dan 2K (default). 4K tidak didukung.

  • Metode 2: Tentukan lebar dan tinggi dalam piksel untuk gambar yang dihasilkan

    • Dalam semua skenario, total piksel antara 768×768 hingga 2048×2048. Rasio aspek antara 1:8 hingga 8:1.

Nilai piksel gambar output mungkin memiliki sedikit perbedaan dari nilai yang ditentukan.

n int (Opsional)

Penting

Parameter n secara langsung memengaruhi biaya: harga satuan × jumlah gambar yang berhasil dibuat. Konfirmasi harga model sebelum memanggil.

  • Saat mode set gambar dinonaktifkan, nilai ini merepresentasikan jumlah gambar yang akan dibuat. Rentangnya 1 hingga 4. Default 1.

  • Saat mode set gambar diaktifkan, nilai ini merepresentasikan jumlah maksimum gambar yang akan dibuat. Rentangnya 1 hingga 12. Default 12. Jumlah aktual ditentukan oleh model dan tidak akan melebihi n.

thinking_mode boolean (Opsional)

Mengaktifkan mode thinking. Default true. Parameter ini hanya berlaku saat mode set gambar dinonaktifkan dan tidak ada input gambar. Saat diaktifkan, model meningkatkan kemampuan Inferensinya untuk meningkatkan kualitas output, tetapi ini meningkatkan waktu pembuatan.

color_palette array (Opsional)

Tema warna kustom. Array objek, masing-masing dengan warna heksadesimal dan rasio. Harus mencakup 3 hingga 10 warna. Disarankan 8 warna.

Ini tersedia hanya saat mode set gambar dinonaktifkan (enable_sequential=false).

Properti

hex string (Wajib)

Nilai warna dalam format heksadesimal (HEX).

ratio string (Wajib)

Persentase warna. Harus akurat hingga dua tempat desimal (seperti "25.00%"). Jumlah semua nilai rasio harus 100.00%.

Klik untuk melihat contoh input

"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%"
    }
]

watermark bool (Opsional)

Menambahkan label Watermark di pojok kanan bawah gambar dengan teks tetap "AI Generated".

  • false (default)

  • true

seed integer (opsional)

Bibit angka acak. Rentang valid: [0,2147483647].

Menggunakan seed yang sama menghasilkan output serupa. Jika dihilangkan, algoritma menggunakan seed acak.

Catatan: Pembuatan gambar bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya mungkin berbeda.

Parameter respons

Respons berhasil

Simpan task_id untuk menanyakan status dan hasil tugas.

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

Respons error

Pembuatan tugas gagal. Lihat Kode Galat.

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

output object

Informasi output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

request_id string

Pengidentifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan error detail. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

Langkah 2: Tanyakan hasil berdasarkan ID tugas

Singapura

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

Beijing

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

Parameter permintaan

Tanyakan hasil tugas

Ganti {task_id} dengan nilai task_id yang dikembalikan oleh pemanggilan API sebelumnya. task_id berlaku untuk kueri selama 24 jam.

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

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

Parameter path

task_id string (Wajib)

ID tugas.

Parameter respons

Eksekusi tugas berhasil

Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan.

{
    "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
    }
}

Eksekusi tugas abnormal

Jika tugas gagal, bidang code dan message dalam respons menunjukkan penyebab error. Lihat 错误码.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Informasi output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

Transisi status selama polling:

  • PENDING → RUNNING → SUCCEEDED atau FAILED.

  • Status kueri awal biasanya PENDING atau RUNNING.

  • Saat status berubah menjadi SUCCEEDED, respons berisi URL gambar yang dihasilkan.

  • Jika statusnya FAILED, periksa pesan error dan coba ulang tugas.

submit_time string

Waktu saat tugas diajukan. Waktu dalam UTC+8 dan format YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

Waktu saat tugas dieksekusi. Waktu dalam UTC+8 dan format YYYY-MM-DD HH:mm:ss.SSS.

end_time string

Waktu saat tugas selesai. Waktu dalam UTC+8 dan format YYYY-MM-DD HH:mm:ss.SSS.

finished boolean

Menunjukkan apakah tugas telah selesai. Default: false.

choices array

Konten output yang dihasilkan oleh model.

Properti

finish_reason string

Alasan tugas berhenti. stop menunjukkan penyelesaian alami.

message object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pesan. Selalu assistant.

content array

Properti

type string

Nilai: text, image.

text string

Teks yang dihasilkan.

image string

URL gambar yang dihasilkan. Format: PNG.

Tautan berlaku selama 24 jam. Segera unduh gambar.

usage object

Statistik penggunaan untuk permintaan. Hanya hasil yang berhasil yang dihitung.

Properti

image_count integer

Jumlah gambar yang dihasilkan.

size string

Resolusi gambar yang dihasilkan. Contoh: 1376*768.

input_tokens integer

Jumlah token input (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

output_tokens integer

Jumlah token output (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

total_tokens integer

Jumlah total token (tidak dikenai biaya). Penagihan berdasarkan jumlah gambar.

request_id string

Pengidentifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan error detail. Dikembalikan hanya untuk permintaan yang gagal. Lihat 错误码.

Python SDK

Nama parameter SDK sebagian besar konsisten dengan HTTP API.

Tugas pembuatan gambar bisa memakan waktu, sehingga SDK membungkus alur kerja asinkron HTTP. Pemanggilan sinkron dan asinkron didukung.

Durasi tugas tergantung pada panjang antrian dan status layanan.
Penting

Pastikan versi DashScope Python SDK Anda adalah 1.25.15 atau lebih baru. Untuk memperbarui, lihat Instal SDK.

Baik base_url maupun Kunci API bersifat spesifik wilayah. Contoh berikut menggunakan wilayah Singapura:

Singapura

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

China (Beijing)

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Pengeditan gambar

Pemanggilan sinkron

Contoh permintaan
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

# Berikut adalah base_url untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Fungsi encoding Base64 ---
# Format encoding Base64 adalah 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("Format gambar tidak didukung atau tidak dikenali")
    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}"

"""
Metode input gambar:
Berikut tiga metode input gambar. Anda perlu memilih hanya satu.
1. Gunakan URL publik: Metode ini cocok untuk gambar yang dapat diakses publik.
2. Gunakan file lokal: Metode ini cocok untuk pengembangan dan pengujian lokal.
3. Gunakan encoding Base64: Metode ini cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
"""
# [Metode 1] Gunakan URL gambar publik
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"

# [Metode 2] Gunakan file lokal (mendukung path absolut dan relatif)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [Metode 3] Gunakan gambar Base64-encoded
# 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 hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan multi-gambar mendukung resolusi maksimum 2K.
)

# Ekstrak URL gambar hasil dan simpan gambar ke file lokal.
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"
                # URL hasil berlaku selama 24 jam. Silakan unduh tepat waktu.
                urllib.request.urlretrieve(image_url, file_name)
                print(f"Gambar disimpan ke {file_name}")
else:
    print(f"Gagal: status_code={rsp.status_code}, message={rsp.message}")
Contoh respons
URL berlaku selama 24 jam. Segera unduh gambar.
{
    "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
    }
}

Pemanggilan asinkron

Contoh permintaan
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

# Berikut adalah base_url untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Fungsi encoding Base64 ---
# Format encoding Base64 adalah 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("Format gambar tidak didukung atau tidak dikenali.")
    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}"

"""
Metode input gambar:
Tiga metode input gambar disediakan di bawah ini. Pilih salah satu.
1. Gunakan URL publik - cocok untuk gambar yang dapat diakses publik.
2. Gunakan file lokal - cocok untuk pengembangan dan pengujian lokal.
3. Gunakan encoding Base64 - cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
"""
# [Metode 1] Gunakan URL gambar publik
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"

# [Metode 2] Gunakan file lokal (mendukung path absolut dan relatif)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [Metode 3] Gunakan gambar Base64-encoded
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

# Buat tugas asinkron.
def create_async_task():
    print("Membuat tugas asinkron...")
    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 hanya mendukung resolusi 4K untuk skenario pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan kolase mendukung resolusi maksimum 2K.
    )

    if response.status_code == 200:
        print("Tugas berhasil dibuat:", response)
        return response
    else:
        raise Exception(f"Gagal membuat tugas: {response.code} - {response.message}")

# Tunggu hingga tugas selesai.
def wait_for_completion(task_response):
    print("Menunggu tugas selesai...")
    status = ImageGeneration.wait(task=task_response, api_key=api_key)

    if status.output.task_status == "SUCCEEDED":
        print("Tugas berhasil!")
        # Ekstrak URL gambar hasil dan simpan gambar ke file lokal.
        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"
                    # URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                    urllib.request.urlretrieve(image_url, file_name)
                    print(f"Gambar disimpan ke {file_name}")
    else:
        raise Exception(f"Tugas gagal dengan status: {status.output.task_status}")

# Dapatkan informasi tentang tugas asinkron.
def fetch_task_status(task):
    print("Mengambil status tugas...")
    status = ImageGeneration.fetch(task=task, api_key=api_key)

    if status.status_code == HTTPStatus.OK:
        print("Status tugas:", status.output.task_status)
        print("Detail respons:", status)
    else:
        print(f"Gagal mengambil status: {status.code} - {status.message}")

# Batalkan tugas asinkron.
def cancel_task(task):
    print("Membatalkan tugas...")
    response = ImageGeneration.cancel(task=task, api_key=api_key)

    if response.status_code == HTTPStatus.OK:
        print("Tugas berhasil dibatalkan:", response.output.task_status)
    else:
        print(f"Gagal membatalkan tugas: {response.code} - {response.message}")

# Alur eksekusi utama.
if __name__ == "__main__":
    task = create_async_task()
    wait_for_completion(task)
Contoh respons
  1. Contoh respons untuk membuat tugas

    {
        "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
        }
    }
  2. Contoh respons untuk menanyakan hasil tugas

    URL berlaku selama 24 jam. Segera unduh gambar.
    {
        "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
        }
    }

Pembuatan set gambar

Pemanggilan sinkron

Contoh permintaan
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

# Berikut adalah base_url untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Fungsi encoding Base64 ---
# Format encoding Base64 adalah 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("Format gambar tidak didukung atau tidak dikenali")
    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}"

"""
Deskripsi metode input gambar (untuk pembuatan urutan gambar-gambar):
Pilih salah satu dari tiga metode input gambar berikut:
1. Gunakan URL publik - Cocok untuk gambar yang dapat diakses publik.
2. Gunakan file lokal - Cocok untuk pengembangan dan pengujian lokal.
3. Gunakan encoding Base64 - Cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
"""
# [Metode 1] Gunakan URL gambar publik
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [Metode 2] Gunakan file lokal (mendukung path absolut dan relatif)
# image_1 = "file:///path/to/your/image.png"

# [Metode 3] Gunakan gambar Base64-encoded
# 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."
        }
        # Untuk pembuatan urutan gambar-gambar: Hapus komentar baris berikut dan beri komentar pada teks biasa di atas.
        # {"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 hanya mendukung resolusi 4K dalam skenario teks-ke-gambar. Pengeditan gambar dan pembuatan urutan gambar mendukung resolusi maksimum 2K.
)

# Ekstrak URL gambar hasil dan simpan gambar secara lokal.
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"
                # URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                urllib.request.urlretrieve(image_url, file_name)
                print(f"Gambar disimpan ke {file_name}")
else:
    print(f"Gagal: status_code={rsp.status_code}, message={rsp.message}")
Contoh respons
URL berlaku selama 24 jam. Segera unduh gambar.
{
    "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
    }
}

Pemanggilan asinkron

Contoh permintaan
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

# base_url berikut untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# Jika Anda belum mengonfigurasi variabel lingkungan DASHSCOPE_API_KEY, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Fungsi encoding Base64 ---
# Skema URI data Base64 adalah 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("Format gambar tidak didukung atau tidak dikenali")
    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}"

"""
Deskripsi metode input gambar (untuk pembuatan urutan gambar-gambar):
Tiga metode input gambar berikut disediakan. Pilih salah satunya.
1. Gunakan URL publik: Cocok untuk gambar yang dapat diakses publik.
2. Gunakan file lokal: Cocok untuk pengembangan dan pengujian lokal.
3. Gunakan encoding Base64: Cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
"""
# [Metode 1] Gunakan URL gambar publik
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [Metode 2] Gunakan file lokal (path absolut dan relatif didukung)
# image_1 = "file:///path/to/your/image.png"

# [Metode 3] Gunakan gambar Base64-encoded
# 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."
            }
            # Skenario pembuatan urutan gambar-gambar: Hapus komentar baris berikut dan beri komentar pada teks biasa di atas.
            # {"text": "Generate a sequence of four seasonal images based on the style of the reference image."},
            # {"image": image_1}
        ],
    )

    # Kirim tugas asinkron
    print("Mengirim tugas asinkron...")
    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 hanya mendukung resolusi 4K dalam skenario teks-ke-gambar. Pengeditan gambar dan pembuatan urutan gambar mendukung resolusi maksimum 2K.
    )

    if response.status_code == 200:
        print(f"Tugas berhasil dikirim. ID Tugas: {response.output.task_id}")

        # Tunggu hingga tugas selesai
        status = ImageGeneration.wait(task=response, api_key=api_key)

        if status.output.task_status == "SUCCEEDED":
            print("Tugas selesai!")
            # Ekstrak URL gambar hasil dan simpan ke perangkat lokal.
            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"
                        # URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                        urllib.request.urlretrieve(image_url, file_name)
                        print(f"Gambar disimpan ke {file_name}")
        else:
            print(f"Tugas gagal. Status: {status.output.task_status}")
    else:
        print(f"Gagal membuat tugas: {response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {e}")
Contoh respons
  1. Contoh respons untuk membuat tugas

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

    URL berlaku selama 24 jam. Segera unduh gambar.
    {
        "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

Nama parameter SDK sebagian besar konsisten dengan HTTP API.

Tugas pembuatan gambar bisa memakan waktu, sehingga SDK membungkus alur kerja asinkron HTTP. Pemanggilan sinkron dan asinkron didukung.

Penting

Pastikan versi DashScope Java SDK Anda adalah 2.22.13 atau lebih baru.

Singapura

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

China (Beijing)

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Pengeditan gambar

Pemanggilan sinkron

Contoh permintaan
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;

/**
 * Contoh Pemanggilan Sinkron Pengeditan Gambar wan2.7-image-pro
 */
public class Main {

    static {
        // Berikut adalah URL untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Fungsi encoding Base64 ---
    // Format encoding Base64: 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 {
        /*
         * Deskripsi metode input gambar:
         * Tiga metode input gambar disediakan di bawah ini. Pilih salah satu.
         * 1. Gunakan URL publik: Cocok untuk gambar yang dapat diakses publik.
         * 2. Gunakan file lokal: Cocok untuk pengembangan dan pengujian lokal.
         * 3. Gunakan encoding Base64: Cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
         */
        // Metode 1: Gunakan URL gambar publik.
        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";

        // Metode 2: Gunakan file lokal. Path absolut dan relatif didukung.
        // Format: file:// + path file
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // Metode 3: Gunakan gambar Base64-encoded.
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // Bangun pesan input multi-gambar.
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // Input multi-gambar didukung. Anda dapat memberikan beberapa gambar referensi.
                        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") // Untuk wan2.7-image-pro, hanya skenario pembuatan teks-ke-gambar yang mendukung resolusi 4K. Pengeditan gambar dan pembuatan kolase mendukung resolusi maksimum 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());
        }
        // Ekstrak URL gambar hasil dan simpan ke file lokal.
        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";
                    // URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Gambar disimpan ke " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Contoh respons
URL berlaku selama 24 jam. Simpan tepat waktu.
{
    "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": ""
}

Pemanggilan asinkron

Contoh permintaan
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;

/**
 * Contoh Pemanggilan Asinkron Pengeditan Gambar wan2.7-image-pro
 */
public class Main {

    static {
        // URL berikut untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Fungsi encoding Base64 ---
    // Format encoding Base64 adalah 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 {
        /*
         * Deskripsi metode input gambar:
         * Tiga metode input gambar berikut disediakan. Anda dapat memilih salah satunya.
         * 1. Gunakan URL publik - Cocok untuk gambar yang dapat diakses publik.
         * 2. Gunakan file lokal - Cocok untuk pengembangan dan pengujian lokal.
         * 3. Gunakan encoding Base64 - Cocok untuk skenario yang melibatkan gambar pribadi atau memerlukan transmisi terenkripsi.
         */
        // [Metode 1] Gunakan URL gambar publik
        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";

        // [Metode 2] Gunakan file lokal (mendukung path absolut dan relatif)
        // Format wajib: file:// + path file
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // [Metode 3] Gunakan gambar Base64-encoded
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // Bangun pesan input multi-gambar
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // Mendukung input multi-gambar. Anda dapat memberikan beberapa gambar referensi.
                        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") // Model wan2.7-image-pro hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Untuk pengeditan dan pembuatan gambar komposit, resolusi maksimum yang didukung adalah 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("Hasil pembuatan tugas:");
        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();
        // Tunggu hingga tugas selesai
        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);
        // Ambil URL gambar hasil dan simpan ke file lokal
        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";
                    // URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Gambar disimpan ke " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Contoh respons
  1. Contoh respons untuk membuat tugas

    {
        "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
        "output": {
            "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
            "task_status": "PENDING"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
  2. Contoh respons untuk menanyakan hasil tugas

    URL berlaku selama 24 jam. Simpan tepat waktu.
    {
        "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": ""
    }

Pembuatan set gambar

Pemanggilan sinkron

Contoh permintaan
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;

/**
 * Contoh penggunaan wan2.7-image-pro untuk pembuatan seri gambar melalui pemanggilan sinkron di wilayah Singapura.
 */
public class Main {

    static {
        // URL berikut untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Fungsi encoding Base64 ---
    // Format untuk encoding Base64 adalah 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 {
        /*
         * Metode input gambar (untuk pembuatan seri gambar-gambar):
         * Tiga metode input gambar disediakan di bawah ini. Pilih salah satu.
         * 1. URL publik: Cocok untuk gambar yang sudah dapat diakses publik.
         * 2. File lokal: Cocok untuk pengembangan dan pengujian lokal.
         * 3. Encoding Base64: Cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
         */
        // Metode 1: Gunakan URL gambar publik
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // Metode 2: Gunakan file lokal (mendukung path absolut dan relatif)
        // Format: file:// + path file
        // String image1 = "file:///path/to/your/image.png";

        // Metode 3: Gunakan gambar Base64-encoded
        // String image1 = encodeFile("/path/to/your/image.png");

        // Bangun pesan input teks. Ini mendukung pembuatan seri teks-ke-gambar dan gambar-ke-gambar. Contoh ini menunjukkan pembuatan seri teks-ke-gambar.
        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();
        // Untuk pembuatan seri gambar-gambar, hapus komentar kode berikut dan beri komentar pada pembangun pesan teks biasa di atas.
        // 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") // Model wan2.7-image-pro hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan seri gambar mendukung resolusi maksimum 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());
        }
        // Ekstrak URL gambar hasil dan simpan ke direktori lokal.
        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";
                    // URL hasil berlaku selama 24 jam. Pastikan untuk mengunduhnya tepat waktu.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Gambar disimpan ke " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Contoh respons
URL berlaku selama 24 jam. Simpan tepat waktu.
{
    "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": ""
}

Pemanggilan asinkron

Contoh permintaan
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;

/**
 * Pembuatan Set Gambar wan2.7-image-pro - Contoh Pemanggilan Asinkron (Wilayah Singapura)
 */
public class Main {

    static {
        // URL berikut untuk wilayah Singapura. base_url bervariasi berdasarkan wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Fungsi encoding Base64 ---
    // Format encoding Base64 adalah 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 {
        /*
         * Deskripsi metode input gambar (untuk skenario pembuatan set gambar-gambar):
         * Tiga metode input gambar berikut disediakan. Anda dapat memilih salah satunya.
         * 1. Gunakan URL publik - cocok untuk gambar yang dapat diakses publik.
         * 2. Gunakan file lokal - cocok untuk pengembangan dan pengujian lokal.
         * 3. Gunakan encoding Base64 - cocok untuk gambar pribadi atau skenario yang memerlukan transmisi terenkripsi.
         */
        // [Metode 1] Gunakan URL gambar publik
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // [Metode 2] Gunakan file lokal (mendukung path absolut dan relatif)
        // Format: file:// + path file
        // String image1 = "file:///path/to/your/image.png";

        // [Metode 3] Gunakan gambar Base64-encoded
        // String image1 = encodeFile("/path/to/your/image.png");

        // Bangun pesan input teks (mendukung pembuatan set teks-ke-gambar dan gambar-ke-gambar. Contoh ini menggunakan pembuatan set teks-ke-gambar.)
        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();
        // Untuk skenario pembuatan set gambar-gambar: hapus komentar kode berikut dan beri komentar pada konstruksi teks biasa di atas.
        // 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") // Model wan2.7-image-pro hanya mendukung resolusi 4K untuk pembuatan teks-ke-gambar. Pengeditan gambar dan pembuatan set gambar mendukung resolusi maksimum 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("Tugas dibuat: " + JsonUtils.toJson(taskResult));

        // Tunggu hingga tugas selesai.
        String taskId = taskResult.getOutput().getTaskId();
        ImageGenerationResult result = waitTask(taskId);
        // Ambil URL gambar hasil dan simpan ke direktori lokal.
        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";
                    // URL hasil berlaku selama 24 jam. Unduh gambar tepat waktu.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Gambar disimpan ke " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Contoh respons
  1. Contoh respons untuk membuat tugas

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

    URL berlaku selama 24 jam. Simpan tepat waktu.
    {
        "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": ""
    }

Penagihan dan pembatasan laju

  • Untuk kuota gratis dan harga satuan model, lihat Harga model.

  • Untuk pembatasan laju model, lihat Wanxiang.

  • Detail penagihan: Anda ditagih berdasarkan jumlah gambar yang berhasil dihasilkan. Pemanggilan yang gagal dan error pemrosesan tidak dikenai biaya atau mengurangi kuota gratis untuk pengguna baru Anda.

Kode error

Jika panggilan model gagal dan mengembalikan pesan kesalahan, lihat Kode Kesalahan untuk resolusi.