全部产品
Search
文档中心

Alibaba Cloud Model Studio:Qwen - Referensi API pengeditan gambar

更新时间:Feb 10, 2026

Model pengeditan gambar Qwen mendukung input dan output multi-gambar. Model ini dapat memodifikasi teks dalam gambar secara akurat, menambahkan atau menghapus objek, menyesuaikan pose subjek, mentransfer gaya gambar, serta meningkatkan detail gambar.

Ikhtisar model

Input image 1

Input image 2

Input image 3

Output images (multiple images)

image99

image98

image89

image100

imageout2

Petunjuk input: Gadis di Image 1 mengenakan gaun hitam dari Image 2 dan duduk dalam pose dari Image 3.

Model

Deskripsi

Spesifikasi gambar output

qwen-image-edit-max

Saat ini memiliki kemampuan yang sama dengan qwen-image-edit-max-2026-01-16

Mendukung pengeditan gambar tunggal dan fusi multi-gambar.

  • Mendukung pembuatan 1 hingga 6 gambar per permintaan.

  • Mendukung resolusi kustom.

  • Mendukung prompt rewriting cerdas.

Format: PNG
Resolusi:

  • Kustom: Gunakan parameter <a baseurl="t3060530_v4_0_0.xdita" data-node="6000169" data-root="85177" data-tag="xref" href="#0e360df4915xx" id="35a61f0a49zg9">parameters.size</a> untuk menentukan width*height gambar keluaran dalam piksel.

  • Bawaan (jika tidak ditentukan): Resolusi output sekitar 1024*1024 piksel, mempertahankan rasio aspek gambar input (atau gambar terakhir dalam permintaan multi-gambar).

qwen-image-edit-max-2026-01-16

qwen-image-edit-plus

Saat ini memiliki kemampuan yang sama dengan qwen-image-edit-plus-2025-10-30

qwen-image-edit-plus-2025-12-15

qwen-image-edit-plus-2025-10-30

qwen-image-edit

Mendukung pengeditan gambar tunggal dan fusi multi-gambar.

  • Mendukung pembuatan satu gambar per permintaan.

  • Tidak mendukung resolusi kustom.

Format: PNG.

Resolusi: Tidak dapat dikustomisasi. Resolusi output mengikuti perilaku bawaan yang dijelaskan di atas.

Catatan

Sebelum memanggil API, lihat Models untuk setiap wilayah.

Prasyarat

Sebelum melakukan panggilan, dapatkan Kunci API dan atur Kunci API sebagai Variabel lingkungan.

Untuk memanggil API menggunakan SDK, instal SDK DashScope. SDK tersedia untuk Python dan Java.

Penting

Wilayah Beijing dan Singapura memiliki Kunci API dan titik akhir permintaan yang terpisah. Jangan menggunakannya secara bergantian. Pemanggilan lintas wilayah akan menyebabkan kegagalan otentikasi atau kesalahan layanan.

HTTP

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

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

Parameter permintaan

Pengeditan gambar tunggal

Contoh ini menunjukkan cara menggunakan model qwen-image-edit-max untuk menghasilkan dua gambar.

curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-edit-max",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/fpakfo/image36.webp"
                    },
                    {
                        "text": "Generate an image that matches the depth map, following this description: A dilapidated red bicycle is parked on a muddy path with a dense primeval forest in the background."
                    }
                ]
            }
        ]
    },
    "parameters": {
        "n": 2,
        "negative_prompt": " ",
        "prompt_extend": true,
        "watermark": false,
        "size": "1536*1024"
    }
}'

Fusi multi-gambar

Contoh ini menunjukkan cara menggunakan model qwen-image-edit-max untuk menghasilkan dua gambar.

curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-edit-max",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"
                    },
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"
                    },
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"
                    },
                    {
                        "text": "Make the girl from Image 1 wear the black dress from Image 2 and sit in the pose from Image 3."
                    }
                ]
            }
        ]
    },
    "parameters": {
        "n": 2,
        "negative_prompt": " ",
        "prompt_extend": true,
        "watermark": false,
        "size": "1024*1536"
    }
}'
Header

Content-Type string (Wajib)

Tipe konten permintaan. Harus berupa application/json.

Authorization string (Wajib)

Kredensial otentikasi menggunakan Kunci API Model Studio.

Contoh: Bearer sk-xxxx

Isi permintaan

model string (Wajib)

Nama model. Contoh nilai: qwen-image-edit-max.

input object (Wajib)

Objek input, yang berisi bidang-bidang berikut:

Properti

messages array (Wajib)

Hanya percakapan satu putaran yang didukung. Array ini harus berisi tepat satu objek pesan. Objek ini berisi properti role dan content.

Properti

role string (Wajib)

Peran pengirim pesan. Nilai ini harus diatur ke user.

content array (Wajib)

Isi pesan: array yang berisi 1 hingga 3 gambar (dalam format {"image": "..."}) dan satu instruksi teks (dalam format {"text": "..."}).

Properti

image string (Wajib)

Gambar input, ditentukan sebagai URL atau string yang di-encode Base64. Anda dapat memberikan 1 hingga 3 gambar per permintaan.

Untuk input multi-gambar, gambar dirujuk berdasarkan posisinya dalam array (Image 1, Image 2, Image 3). Rasio aspek gambar output ditentukan oleh gambar terakhir.

Persyaratan gambar:

  • Format gambar: JPG, JPEG, PNG, BMP, TIFF, WEBP, dan GIF.

    Gambar output dalam format PNG. Untuk GIF animasi, hanya frame pertama yang diproses.
  • Resolusi gambar: Untuk hasil optimal, lebar dan tinggi harus antara 384 hingga 3072 piksel. Gambar beresolusi rendah dapat menghasilkan output buram, sedangkan gambar beresolusi tinggi meningkatkan waktu pemrosesan.

  • Ukuran file maksimum: 10 MB.

Format input yang didukung:

  1. URL publik

    • Mendukung HTTP dan HTTPS.

    • Contoh: https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/fpakfo/image36.webp

  2. String gambar yang di-encode Base64

text string (Wajib)

Instruksi pengeditan gambar (positive prompt) yang menjelaskan elemen dan fitur visual yang Anda inginkan dalam gambar yang dihasilkan.

Saat menggunakan beberapa gambar, rujuk sebagai "Image 1", "Image 2", dan "Image 3" dalam prompt Anda agar model dapat memetakan instruksi Anda dengan benar.

Parameter ini mendukung Bahasa Mandarin Sederhana dan Bahasa Inggris dengan panjang maksimum 800 karakter. Setiap karakter Mandarin atau huruf Inggris dihitung sebagai satu karakter. Konten yang melebihi batas akan dipotong secara otomatis.

Contoh: Buat gadis dari Image 1 mengenakan gaun hitam dari Image 2 dan duduk dalam pose dari Image 3. Pertahankan pakaian, gaya rambut, dan ekspresinya, serta pastikan gerakannya alami dan lancar.

parameters object (Opsional)

Parameter tambahan untuk mengontrol pembuatan gambar.

Properti

n integer (Opsional)

Jumlah gambar yang akan dihasilkan. Nilai bawaan adalah 1.

Untuk model seri qwen-image-edit-max dan qwen-image-edit-plus, Anda dapat menghasilkan 1 hingga 6 gambar.

Untuk qwen-image-edit, hanya satu gambar yang dapat dihasilkan.

negative_prompt string (Opsional)

Prompt negatif, yang menjelaskan konten yang tidak Anda inginkan dalam gambar yang dihasilkan.

Parameter ini mendukung Bahasa Mandarin Sederhana dan Bahasa Inggris dengan panjang maksimum 500 karakter. Setiap karakter Mandarin atau huruf Inggris dihitung sebagai satu karakter. Konten yang melebihi batas akan dipotong secara otomatis.

Contoh: low resolution, error, worst quality, low quality, disfigured, extra fingers, bad proportions.

size string (Opsional)

Menentukan resolusi gambar output dalam format width*height, seperti "1024*1536". Nilai lebar dan tinggi harus dalam rentang [512, 2048] piksel.

Resolusi yang direkomendasikan untuk rasio aspek umum

  • 1:1: 1024*1024, 1536*1536

  • 2:3: 768*1152, 1024*1536

  • 3:2: 1152*768, 1536*1024

  • 3:4: 960*1280, 1080*1440

  • 4:3: 1280*960, 1440*1080

  • 9:16: 720*1280, 1080*1920

  • 16:9: 1280*720, 1920*1080

  • 21:9: 1344*576, 2048*872

Aturan ukuran gambar output

  • Setel size: Sistem mengubah ukuran gambar output ke lebar dan tinggi terdekat yang merupakan kelipatan 16, berdasarkan size yang ditentukan. Misalnya, jika Anda menyetel 1033*1032, ukuran gambar output menjadi 1040*1024.

  • Jika Anda tidak menyetel parameter ini, gambar output mempertahankan rasio aspek yang mirip dengan gambar input atau gambar terakhir dalam input multi-gambar, dengan resolusi mendekati 1024*1024.

Model yang didukung: model seri qwen-image-edit-max dan qwen-image-edit-plus.

prompt_extend bool (Opsional)

Menentukan apakah akan mengaktifkan prompt rewriting, yang secara bawaan aktif (true). Saat diaktifkan, model mengoptimalkan positive prompt (text). Fitur ini secara signifikan meningkatkan hasil ketika prompt kurang detail.

Model yang didukung: model seri qwen-image-edit-max dan qwen-image-edit-plus.

watermark bool (Opsional)

Menentukan apakah akan menambahkan watermark "Qwen-Image" di pojok kanan bawah gambar. Nilai bawaan adalah false. Watermark:

1

seed integer (Opsional)

Seed bilangan acak. Nilainya harus berupa integer dalam rentang [0, 2147483647].

Menggunakan nilai seed yang sama membantu memastikan konsistensi dalam konten yang dihasilkan.

Catatan: Proses pembuatan model bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya mungkin masih berbeda antar permintaan.

Parameter respons

Respons 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": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "width": 1536,
        "image_count": 2,
        "height": 1024
    },
    "request_id": "bf37ca26-0abe-98e4-8065-xxxxxx"
}

Respons Kesalahan

Jika tugas gagal, respons akan mengembalikan informasi terkait. Anda dapat mengidentifikasi penyebab kegagalan dari bidang kode dan pesan. Untuk informasi lebih lanjut tentang cara menyelesaikan kesalahan, lihat Kode kesalahan.

{
    "request_id": "31f808fd-8eef-9004-xxxxx",
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided."
}

output object

Hasil yang dihasilkan oleh model.

Properti

choices array

Daftar hasil yang dihasilkan.

Properti

finish_reason string

Alasan tugas pembuatan dihentikan. Nilai stop menunjukkan bahwa tugas berhasil diselesaikan.

message object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pengirim pesan. Nilainya adalah assistant.

content array

Isi pesan, yang berisi informasi tentang gambar yang dihasilkan.

Properti

image string

URL gambar PNG yang dihasilkan. Tautan ini kedaluwarsa setelah 24 jam, jadi segera unduh dan simpan gambarnya.

usage object

Penggunaan resource untuk permintaan ini. Parameter ini hanya dikembalikan saat permintaan berhasil.

Properti

image_count integer

Jumlah gambar yang dihasilkan.

width integer

Lebar gambar yang dihasilkan dalam piksel.

height integer

Tinggi gambar yang dihasilkan dalam piksel.

request_id string

Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah.

code string

Kode kesalahan. Hanya dikembalikan saat permintaan gagal. Lihat kode kesalahan untuk detailnya.

message string

Pesan kesalahan detail. Hanya dikembalikan saat permintaan gagal. Lihat kode kesalahan untuk detailnya.

DashScope SDK

Nama parameter SDK sebagian besar konsisten dengan API HTTP. Untuk daftar lengkap parameter, lihat Referensi API Qwen.

Python SDK

Catatan
  • Instal versi terbaru SDK Python DashScope. Jika tidak, kesalahan waktu proses dapat terjadi: Instal atau upgrade SDK.

  • API asinkron tidak didukung.

Contoh permintaan

Contoh ini menggunakan model qwen-image-edit-max untuk menghasilkan dua gambar.

Kirim gambar menggunakan URL publik

import json
import os
import dashscope
from dashscope import MultiModalConversation

# Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Model mendukung satu hingga tiga gambar input.
messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"},
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"},
            {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"},
            {"text": "Make the girl from Image 1 wear the black dress from Image 2 and sit in the pose from Image 3."}
        ]
    }
]

# Wilayah Singapura dan Beijing menggunakan Kunci API terpisah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Ganti dengan Kunci API Anda jika variabel lingkungan belum diatur: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

# Seri qwen-image-edit-max dan qwen-image-edit-plus mendukung output 1 hingga 6 gambar. Contoh ini menunjukkan cara menghasilkan 2 gambar.
response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-edit-max",
    messages=messages,
    stream=False,
    n=2,
    watermark=False,
    negative_prompt=" ",
    prompt_extend=True,
    size="1024*1536",
)

if response.status_code == 200:
    # Untuk melihat respons lengkap, hapus komentar baris berikut.
    # print(json.dumps(response, ensure_ascii=False))
    for i, content in enumerate(response.output.choices[0].message.content):
        print(f"URL of output image {i+1}: {content['image']}")
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")

Kirim gambar menggunakan encoding Base64

import json
import os
import dashscope
from dashscope import MultiModalConversation
import base64
import mimetypes

# Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'


# --- Untuk encoding Base64 ---
# Format: 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")

    try:
        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}"
    except IOError as e:
        raise IOError(f"Error reading file: {file_path}, Error: {str(e)}")


# Dapatkan encoding Base64 gambar.
# Panggil fungsi encoding. Ganti "/path/to/your/image.png" dengan path ke file gambar lokal Anda.
image = encode_file("/path/to/your/image.png")

messages = [
    {
        "role": "user",
        "content": [
            {"image": image},
            {"text": "Generate an image that matches the depth map, following this description: A dilapidated red bicycle is parked on a muddy path with a dense primeval forest in the background."}
        ]
    }
]

# Wilayah Singapura dan Beijing menggunakan Kunci API terpisah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Ganti dengan Kunci API Anda jika variabel lingkungan belum diatur: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

# Seri qwen-image-edit-max dan qwen-image-edit-plus mendukung output 1 hingga 6 gambar. Contoh ini menunjukkan cara menghasilkan 2 gambar.
response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-edit-max",
    messages=messages,
    stream=False,
    n=2,
    watermark=False,
    negative_prompt=" ",
    prompt_extend=True,
    size="1920*1080",
)

if response.status_code == 200:
    # Untuk melihat respons lengkap, hapus komentar baris berikut.
    # print(json.dumps(response, ensure_ascii=False))
    for i, content in enumerate(response.output.choices[0].message.content):
        print(f"URL of output image {i+1}: {content['image']}")
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")

Unduh gambar dari URL

# Instal library requests terlebih dahulu: pip install requests
import requests


def download_image(image_url, save_path='output.png'):
    try:
        response = requests.get(image_url, stream=True, timeout=300)  # Setel timeout
        response.raise_for_status()  # Bangkitkan pengecualian jika kode status HTTP bukan 200.
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        print(f"Image downloaded successfully to: {save_path}")

    except requests.exceptions.RequestException as e:
        print(f"Image download failed: {e}")


image_url = "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
download_image(image_url, save_path='output.png')

Contoh respons

Tautan gambar berlaku selama 24 jam. Segera unduh gambarnya.

input_tokens dan output_tokens adalah bidang kompatibilitas, saat ini tetap 0.
{
    "status_code": 200,
    "request_id": "fa41f9f9-3cb6-434d-a95d-4ae6b9xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ],
        "audio": null
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0,
        "height": 1536,
        "image_count": 2,
        "width": 1024
    }
}

Java SDK

Catatan

Instal versi terbaru SDK Java DashScope. Jika tidak, kesalahan waktu proses dapat terjadi. Lihat Instal atau upgrade SDK.

Contoh permintaan

Contoh berikut menunjukkan cara menggunakan model qwen-image-edit-max untuk menghasilkan dua gambar.

Kirim gambar menggunakan URL publik

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

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

public class QwenImageEdit {

    static {
        // URL berikut untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/api/v1.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }
    
    // Wilayah Singapura dan Beijing menggunakan Kunci API terpisah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key.
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

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

        MultiModalConversation conv = new MultiModalConversation();

        // Model mendukung satu hingga tiga gambar input.
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"),
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"),
                        Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"),
                        Collections.singletonMap("text", "Make the girl from Image 1 wear the black dress from Image 2 and sit in the pose from Image 3.")
                )).build();
        // qwen-image-edit-max dan qwen-image-edit-plus mendukung output 1 hingga 6 gambar. Contoh ini menunjukkan cara menghasilkan 2 gambar.
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        parameters.put("n", 2);
        parameters.put("prompt_extend", true);
        parameters.put("size", "1024*1536");

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

        MultiModalConversationResult result = conv.call(param);
        // Untuk melihat respons lengkap, hapus komentar baris berikut.
        // System.out.println(JsonUtils.toJson(result));
        List<Map<String, Object>> contentList = result.getOutput().getChoices().get(0).getMessage().getContent();
        int imageIndex = 1;
        for (Map<String, Object> content : contentList) {
            if (content.containsKey("image")) {
                System.out.println("URL of output image " + imageIndex + ": " + content.get("image"));
                imageIndex++;
            }
        }
    }

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

Kirim gambar menggunakan encoding Base64

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public class QwenImageEdit {

    static {
        // URL berikut untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/api/v1.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }
    
    // Wilayah Singapura dan Beijing menggunakan Kunci API terpisah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key.
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

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

        // Ganti "/path/to/your/image.png" dengan path ke file gambar lokal Anda.
        String image = encodeFile("/path/to/your/image.png");

        MultiModalConversation conv = new MultiModalConversation();

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", image),
                        Collections.singletonMap("text", "Generate an image that matches the depth map, following this description: A dilapidated red bicycle is parked on a muddy path with a dense primeval forest in the background.")
                )).build();
        // qwen-image-edit-max dan qwen-image-edit-plus mendukung output 1 hingga 6 gambar. Contoh ini menunjukkan cara menghasilkan 2 gambar.
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        parameters.put("n", 2);
        parameters.put("prompt_extend", true);
        parameters.put("size", "1536*1024");

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

        MultiModalConversationResult result = conv.call(param);
        // Untuk melihat respons lengkap, hapus komentar baris berikut.
        // System.out.println(JsonUtils.toJson(result));
        List<Map<String, Object>> contentList = result.getOutput().getChoices().get(0).getMessage().getContent();
        int imageIndex = 1;
        for (Map<String, Object> content : contentList) {
            if (content.containsKey("image")) {
                System.out.println("URL of output image " + imageIndex + ": " + content.get("image"));
                imageIndex++;
            }
        }
    }

    /**
     * Meng-encode file menjadi string Base64.
     * @param filePath Path file.
     * @return String Base64 dalam format: data:{mime_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("File does not exist: " + filePath);
        }
        // Deteksi tipe MIME.
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to detect the file type: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("Unsupported or unrecognized image format.");
        }
        // Baca konten file dan encode-nya.
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read the file content: " + filePath);
        }

        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

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

Unduh gambar dari URL

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class ImageDownloader {
    public static void downloadImage(String imageUrl, String savePath) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(300000);
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(savePath);
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();
 
            System.out.println("Image downloaded successfully to: " + savePath);
        } catch (Exception e) {
            System.err.println("Image download failed: " + e.getMessage());
        }
    }
 
    public static void main(String[] args) {
        String imageUrl = "http://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx?Expires=xxx";
        String savePath = "output.png";
        downloadImage(imageUrl, savePath);
    }
}

Contoh respons

Tautan gambar berlaku selama 24 jam. Segera unduh gambarnya.

{
    "requestId": "46281da9-9e02-941c-ac78-be88b8xxxxxx",
    "usage": {
        "image_count": 2,
        "width": 1024,
        "height": 1536
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        },
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    }
}

Konfigurasikan izin akses gambar

Gambar yang dihasilkan oleh model disimpan di Object Storage Service (OSS). Setiap gambar yang dihasilkan diberi tautan OSS yang dapat diakses publik, seperti https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png. Anda dapat menggunakan tautan ini untuk melihat atau mengunduh gambar, tetapi tautan tersebut kedaluwarsa setelah 24 jam.

Jika kebijakan keamanan Anda membatasi akses ke tautan OSS publik, tambahkan nama domain berikut ke daftar putih Anda untuk memastikan Anda dapat mengakses gambar yang dihasilkan.

dashscope-result-bj.oss-cn-beijing.aliyuncs.com
dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

Kode kesalahan

Jika panggilan gagal, lihat Pesan kesalahan untuk troubleshooting.

Penagihan dan pembatasan laju

  • Untuk harga model dan kuota gratis, lihat Daftar dan Harga Model.

  • Untuk batas throttling, lihat Batas laju.

  • Deskripsi penagihan: Anda dikenai biaya berdasarkan jumlah gambar yang berhasil dihasilkan. Panggilan model yang gagal atau kesalahan pemrosesan tidak dikenai biaya atau mengurangi kuota gratis.

FAQ

T: Bahasa apa saja yang didukung oleh model pengeditan gambar Qwen?

J: Model ini secara resmi mendukung Bahasa Mandarin Sederhana dan Bahasa Inggris. Bahasa lain mungkin berfungsi, tetapi hasilnya tidak dijamin.

T: Saat mengunggah beberapa gambar referensi dengan rasio aspek berbeda, bagaimana rasio aspek output ditentukan?

J: Secara bawaan, rasio aspek gambar output sesuai dengan gambar terakhir dalam array input. Perilaku ini dapat diganti dengan menentukan parameter parameters.size.

T: Bagaimana cara melihat penggunaan model?

J: Untuk informasi lebih lanjut, lihat Inkuiri Penagihan dan Manajemen Biaya.