Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Wan2.7 - generación y edición de imágenes

Última actualización: Oct 12, 2026

Wan2.7-Image admite texto a imagen, texto a conjunto de imágenes, imagen a conjunto de imágenes, edición de imágenes y generación de referencia de múltiples imágenes.

Resumen de modelos

Modelo

Descripción

Especificaciones de la imagen de salida

wan2.7-image-pro

Imagen Pro Wan 2.7. Admite salida 4K para generación de texto a imagen (no para conjuntos de imágenes).

Formato de imagen: PNG.

Para la resolución y las dimensiones de la imagen, consulte el parámetro size.

wan2.7-image

Imagen Wan 2.7. Generación más rápida.

NotaAntes de llamar a un modelo, consulte Lista de modelos y precios para verificar la disponibilidad regional del modelo.

Requisitos previos

Obtenga una clave API y exporte la clave API como variable de entorno.

ImportanteLas regiones de China (Pekín) y Singapur tienen claves de API y endpoints de solicitud separados. No pueden utilizarse indistintamente. Las llamadas entre regiones provocan fallos de autenticación o errores de servicio.

HTTP síncrono

Devuelve el resultado en una sola solicitud. Recomendado para la mayoría de los casos de uso.

Singapore

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

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Beijing

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

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Parámetros de solicitud

Texto a imagen

El modelo wan2.7-image-pro admite resolución 4K únicamente para la generación de texto a imagen. La edición de imágenes y la generación de conjuntos de imágenes admiten hasta resolución 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
        }
    }'

Edición de imagen

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

Edición interactiva

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

Generación de conjunto de imágenes

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

Encabezados

Content-Type string (Requerido)

El tipo de contenido de la solicitud. Debe ser application/json.

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

Cuerpo de la solicitud

model string (Obligatorio)

El nombre del modelo. Valores válidos: wan2.7-image-pro, wan2.7-image.

input object (Obligatorio)

El objeto de entrada.

Propiedades

messages array (Obligatorio)

Una matriz de contenido de solicitud. Solo se admiten conversaciones de un solo turno.

Propiedades

role string (Obligatorio)

El rol del mensaje. Debe ser user.

content array (Obligatorio)

Una matriz de contenido de mensajes.

Propiedades

text string

El indicador de texto. Admite chino e inglés. Máximo de 5,000 caracteres. Cada carácter, letra, número o símbolo cuenta como uno. Los caracteres excedentes se truncan.

imagen string

La URL o la cadena codificada en Base64 de la imagen de entrada.

Límites de imagen:

  • Formato de imagen: JPEG, JPG, PNG (no se admiten canales alfa), BMP, WEBP.
  • Resolución de imagen: El ancho y el alto deben estar entre 240 y 8,000 píxeles. La relación de aspecto debe estar entre 1:8 y 8:1.
  • Tamaño de archivo: No más de 20 MB.

Límites de cantidad de imágenes:

  • Puede ingresar de 0 a 9 imágenes.
  • Cuando introduce múltiples imágenes, debe pasar múltiples objetos image en la matriz content. El orden de los objetos en la matriz determina el orden de las imágenes.

Formatos de entrada admitidos:

  1. Utilizar una URL accesible públicamente

    • Admite protocolos HTTP o HTTPS.
    • Ejemplo: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pasar una cadena de imagen codificada en Base64

    • Formato: data:{MIME_type};base64,{base64_data}
    • Ejemplo: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (Esto es solo con fines ilustrativos. Debe pasar la cadena completa.)
    • Para obtener más información, consulte Métodos de entrada de imagen.

parameters object (Opcional)

Configuración de parámetros del modelo.

Propiedades

bbox_list List[List[List[int]]] (Opcional)

El área del cuadro delimitador para la edición interactiva.

  • La longitud de la lista debe coincidir con el número de imágenes de entrada. Si una imagen no requiere edición, pase una lista vacía [] en la posición correspondiente.
  • Formato de coordenadas: [x1, y1, x2, y2] (x superior izquierda, y superior izquierda, x inferior derecha, y inferior derecha). Utilice coordenadas absolutas en píxeles de la imagen original. La coordenada superior izquierda es (0, 0).
  • Una sola imagen admite un máximo de dos cuadros delimitadores.

Ejemplo: Entrada de 3 imágenes, donde la segunda imagen no tiene cuadro delimitador y la primera imagen tiene dos cuadros delimitadores:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # Image 1 (2 boxes)
  [],                                    # Image 2 (no box)
  [[10, 10, 50, 50]]                     # Image 3 (1 box)
]

enable_sequential boolean (Opcional)

Controla el modo de generación de imágenes:

  • false (predeterminado): El modo de salida predeterminado.
  • true: El modo de salida de conjunto de imágenes.

size string (Opcional)

La resolución de la imagen de salida. Admite dos métodos mutuamente excluyentes:

Modelo: wan2.7-image-pro
  • Método 1: Especificar la resolución de la imagen de salida (Recomendado)
    • Admite especificaciones de 1K, 2K (predeterminado) y 4K.

    • Ámbito de aplicación:

      • Texto a imagen (sin entrada de imagen, no para generación de conjuntos de imágenes): Admite 1K, 2K y 4K.
      • Otros escenarios: Admite 1K y 2K.
    • Píxeles totales para cada especificación: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096

    • Relación de aspecto de la imagen:

      • Cuando se introduce una imagen: La relación de aspecto de salida coincide con la imagen de entrada (la última si se introducen varias imágenes) y se escala a la resolución seleccionada.
      • Cuando no se ingresa ninguna imagen: La salida es una imagen cuadrada.
  • Método 2: Especificar el ancho y alto en píxeles para la imagen generada
    • Texto a imagen: Los píxeles totales están entre 768×768 y 4096×4096. La relación de aspecto está entre 1:8 y 8:1.
    • Otros escenarios: Los píxeles totales están entre 768×768 y 2048×2048. La relación de aspecto está entre 1:8 y 8:1.
Modelo: wan2.7-image
  • Método 1: Especificar la resolución de la imagen de salida (Recomendado)
    • Admite especificaciones de 1K y 2K (predeterminado). No se admite 4K.
  • Método 2: Especificar el ancho y alto en píxeles para la imagen generada
    • En todos los escenarios, los píxeles totales están entre 768×768 y 2048×2048. La relación de aspecto está entre 1:8 y 8:1.

Los valores de píxeles de la imagen de salida pueden tener diferencias menores respecto a los valores especificados.

n int (Opcional)

ImportanteEl parámetro n afecta directamente al costo: precio unitario × número de imágenes generadas exitosamente. Confirme los precios del modelo antes de realizar la llamada.

  • Cuando el modo de conjunto de imágenes está desactivado, este valor representa la cantidad de imágenes a generar. El rango es de 1 a 4. El valor predeterminado es 1.
  • Cuando el modo de conjunto de imágenes está activado, este valor representa el número máximo de imágenes a generar. El rango es de 1 a 12. El valor predeterminado es 12. El número real lo determina el modelo y no excederá n.

thinking_mode boolean (Opcional)

Activa el modo de pensamiento. El valor predeterminado es true. Este parámetro solo es efectivo cuando el modo de conjunto de imágenes está desactivado y no se introduce ninguna imagen. Cuando está activado, el modelo mejora sus capacidades de inferencia para aumentar la calidad de la salida, pero esto incrementa el tiempo de generación.

color_palette array (Opcional)

Un tema de color personalizado. Una matriz de objetos, cada uno con un color hexadecimal y una proporción. Debe incluir de 3 a 10 colores. Se recomiendan 8 colores.

Esto está disponible solo cuando el modo de conjunto de imágenes está deshabilitado (enable_sequential=false).

Propiedades

hex string (Obligatorio)

El valor de color en formato hexadecimal (HEX).

ratio string (Obligatorio)

El porcentaje del color. Debe tener una precisión de dos decimales (como "25.00%"). La suma de todos los valores de proporción debe ser 100.00%.

Haga clic para ver un ejemplo de entrada

"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 (Opcional)

Añade una etiqueta de marca de agua en la esquina inferior derecha de la imagen con el texto fijo "AI Generated".

  • false (predeterminado)
  • true

seed integer (opcional)

Semilla de número aleatorio. Rango válido: [0,2147483647].

Usar la misma seed produce resultados similares. Si se omite, el algoritmo utiliza una semilla aleatoria.

Nota: La generación de imágenes es probabilística. Incluso con la misma seed, los resultados pueden variar.

Parámetros de respuesta

Ejecución de tarea exitosa

Los datos de la tarea (estado de la tarea y URL de imágenes) se conservan solo durante 24 horas y luego se eliminan automáticamente. Guarde las imágenes generadas con prontitud.

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

Ejecución anómala de la tarea

Si una tarea falla, los campos code y message en la respuesta indican la causa del error. Consulte Códigos de error.

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

output object

Información de salida de la tarea.

Propiedades

choices array

El contenido de salida generado por el modelo.

Propiedades

finish_reason string

La razón por la que se detuvo la tarea. stop indica una finalización natural.

message object

El mensaje devuelto por el modelo.

Propiedades

role string

El rol del mensaje. Siempre assistant.

content array

Propiedades

type string

Valor: image.

imagen string

La URL de la imagen generada. Formato: PNG.

El enlace es válido por 24 horas. Descargue la imagen a la brevedad.

finished boolean

Indica si la tarea ha finalizado. Predeterminado: false.

usage object

Estadísticas de uso para la solicitud. Solo se cuentan los resultados exitosos.

Propiedades

image_count integer

El número de imágenes generadas.

size string

La resolución de la imagen generada. Ejemplo: 1376*768.

input_tokens integer

El número de tokens de entrada (no facturable). La facturación se basa en el número de imágenes.

output_tokens integer

El número de tokens de salida (no facturable). La facturación se basa en el número de imágenes.

total_tokens integer

El número total de tokens (no facturable). La facturación se basa en el número de imágenes.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

asíncrono HTTP

Ideal para tareas de larga duración. Envíe una tarea y luego consulte el estado y los resultados.

Paso 1: Crear una tarea para obtener el ID de tarea

Singapore

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

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Beijing

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

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Parámetros de solicitud

Texto a imagen

El modelo wan2.7-image-pro admite resolución 4K únicamente para la generación de texto a imagen. La edición de imágenes y la generación de conjuntos de imágenes admiten hasta resolución 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
        }
    }'

Edición de imagen

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

Edición interactiva

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

Generación de conjunto de imágenes

El modelo wan2.7-image-pro admite hasta resolución 2K para la generación de conjuntos de imágenes.

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

Encabezados

Content-Type string (Requerido)

El tipo de contenido de la solicitud. Debe ser application/json.

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

X-DashScope-Async string (Requerido)

Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser enable.

ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls".

Cuerpo de la solicitud

model string (Obligatorio)

El nombre del modelo. Valores válidos: wan2.7-image-pro, wan2.7-image.

input object (Obligatorio)

El objeto de entrada.

Propiedades

messages array (Obligatorio)

Una matriz de contenido de solicitud. Solo se admiten conversaciones de un solo turno.

Propiedades

role string (Obligatorio)

El rol del mensaje. Debe ser user.

content array (Obligatorio)

Una matriz de contenido de mensajes.

Propiedades

text string

El indicador de texto. Admite chino e inglés. Máximo de 5,000 caracteres. Cada carácter, letra, número o símbolo cuenta como uno. Los caracteres excedentes se truncan.

imagen string

La URL o la cadena codificada en Base64 de la imagen de entrada.

Límites de imagen:

  • Formato de imagen: JPEG, JPG, PNG (no se admiten canales alfa), BMP, WEBP.
  • Resolución de imagen: El ancho y el alto deben estar entre 240 y 8,000 píxeles. La relación de aspecto debe estar entre 1:8 y 8:1.
  • Tamaño de archivo: No más de 20 MB.

Límites de cantidad de imágenes:

  • Puede ingresar de 0 a 9 imágenes.
  • Cuando introduce múltiples imágenes, debe pasar múltiples objetos image en la matriz content. El orden de los objetos en la matriz determina el orden de las imágenes.

Formatos de entrada admitidos:

  1. Utilizar una URL accesible públicamente

    • Admite protocolos HTTP o HTTPS.
    • Ejemplo: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pasar una cadena de imagen codificada en Base64

    • Formato: data:{MIME_type};base64,{base64_data}
    • Ejemplo: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (Esto es solo con fines ilustrativos. Debe pasar la cadena completa.)
    • Para obtener más información, consulte Métodos de entrada de imagen.

parameters object (Opcional)

Configuración de parámetros del modelo.

Propiedades

bbox_list List[List[List[int]]] (Opcional)

El área del cuadro delimitador para la edición interactiva.

  • La longitud de la lista debe coincidir con el número de imágenes de entrada. Si una imagen no requiere edición, pase una lista vacía [] en la posición correspondiente.
  • Formato de coordenadas: [x1, y1, x2, y2] (x superior izquierda, y superior izquierda, x inferior derecha, y inferior derecha). Utilice coordenadas absolutas en píxeles de la imagen original. La coordenada superior izquierda es (0, 0).
  • Una sola imagen admite un máximo de dos cuadros delimitadores.

Ejemplo: Entrada de 3 imágenes, donde la segunda imagen no tiene cuadro delimitador y la primera imagen tiene dos cuadros delimitadores:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # Image 1 (2 boxes)
  [],                                    # Image 2 (no box)
  [[10, 10, 50, 50]]                     # Image 3 (1 box)
]

enable_sequential boolean (Opcional)

Controla el modo de generación de imágenes:

  • false (predeterminado): El modo de salida predeterminado.
  • true: El modo de salida de conjunto de imágenes.

size string (Opcional)

La resolución de la imagen de salida. Admite dos métodos mutuamente excluyentes:

Modelo: wan2.7-image-pro
  • Método 1: Especificar la resolución de la imagen de salida (Recomendado)
    • Admite especificaciones de 1K, 2K (predeterminado) y 4K.

    • Ámbito de aplicación:

      • Texto a imagen (sin entrada de imagen, no para generación de conjuntos de imágenes): Admite 1K, 2K y 4K.
      • Otros escenarios: Admite 1K y 2K.
    • Píxeles totales para cada especificación: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096

    • Relación de aspecto de la imagen:

      • Cuando se introduce una imagen: La relación de aspecto de salida coincide con la imagen de entrada (la última si se introducen varias imágenes) y se escala a la resolución seleccionada.
      • Cuando no se ingresa ninguna imagen: La salida es una imagen cuadrada.
  • Método 2: Especificar el ancho y alto en píxeles para la imagen generada
    • Texto a imagen: Los píxeles totales están entre 768×768 y 4096×4096. La relación de aspecto está entre 1:8 y 8:1.
    • Otros escenarios: Los píxeles totales están entre 768×768 y 2048×2048. La relación de aspecto está entre 1:8 y 8:1.
Modelo: wan2.7-image
  • Método 1: Especificar la resolución de la imagen de salida (Recomendado)
    • Admite especificaciones de 1K y 2K (predeterminado). No se admite 4K.
  • Método 2: Especificar el ancho y alto en píxeles para la imagen generada
    • En todos los escenarios, los píxeles totales están entre 768×768 y 2048×2048. La relación de aspecto está entre 1:8 y 8:1.

Los valores de píxeles de la imagen de salida pueden tener diferencias menores respecto a los valores especificados.

n int (Opcional)

ImportanteEl parámetro n afecta directamente al costo: precio unitario × número de imágenes generadas exitosamente. Confirme los precios del modelo antes de realizar la llamada.

  • Cuando el modo de conjunto de imágenes está desactivado, este valor representa la cantidad de imágenes a generar. El rango es de 1 a 4. El valor predeterminado es 1.
  • Cuando el modo de conjunto de imágenes está activado, este valor representa el número máximo de imágenes a generar. El rango es de 1 a 12. El valor predeterminado es 12. El número real lo determina el modelo y no excederá n.

thinking_mode boolean (Opcional)

Activa el modo de pensamiento. El valor predeterminado es true. Este parámetro solo es efectivo cuando el modo de conjunto de imágenes está desactivado y no se introduce ninguna imagen. Cuando está activado, el modelo mejora sus capacidades de inferencia para aumentar la calidad de la salida, pero esto incrementa el tiempo de generación.

color_palette array (Opcional)

Un tema de color personalizado. Una matriz de objetos, cada uno con un color hexadecimal y una proporción. Debe incluir de 3 a 10 colores. Se recomiendan 8 colores.

Esto está disponible solo cuando el modo de conjunto de imágenes está deshabilitado (enable_sequential=false).

Propiedades

hex string (Obligatorio)

El valor de color en formato hexadecimal (HEX).

ratio string (Obligatorio)

El porcentaje del color. Debe tener una precisión de dos decimales (como "25.00%"). La suma de todos los valores de proporción debe ser 100.00%.

Haga clic para ver un ejemplo de entrada

"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 (Opcional)

Añade una etiqueta de marca de agua en la esquina inferior derecha de la imagen con el texto fijo "AI Generated".

  • false (predeterminado)
  • true

seed integer (opcional)

Semilla de número aleatorio. Rango válido: [0,2147483647].

Usar la misma seed produce resultados similares. Si se omite, el algoritmo utiliza una semilla aleatoria.

Nota: La generación de imágenes es probabilística. Incluso con la misma seed, los resultados pueden variar.

Parámetros de respuesta

Respuesta exitosa

Guarde el task_id para consultar el estado y el resultado de la tarea.

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

Respuesta de error

Error en la creación de la tarea. Consulte Códigos de error.

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

output object

Información de salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

Paso 2: Consultar el resultado por ID de tarea

Singapore

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}

Parámetros de solicitud

Consultar resultado de la tarea

Reemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

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

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

Parámetros de ruta

task_id string (Obligatorio)

El ID de la tarea.

Parámetros de respuesta

Ejecución de tarea exitosa

Los datos de la tarea (estado de la tarea y URL de imágenes) se conservan solo durante 24 horas y luego se eliminan automáticamente. Guarde las imágenes generadas con prontitud.

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

Ejecución anómala de la tarea

Si una tarea falla, los campos code y message en la respuesta indican la causa del error. Consulte Códigos de error.

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

output object

Información de salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.
Transiciones de estado durante el sondeo:
  • PENDING → RUNNING → SUCCEEDED o FAILED.
  • El estado inicial de la consulta suele ser PENDING o RUNNING.
  • Cuando el estado cambia a SUCCEEDED, la respuesta contiene la URL de la imagen generada.
  • Si el estado es FAILED, revise el mensaje de error y reintente la tarea.

submit_time string

La hora en que se envió la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

La hora en que se ejecutó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

end_time string

La hora en que se completó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

finished boolean

Indica si la tarea ha finalizado. Predeterminado: false.

choices array

El contenido de salida generado por el modelo.

Propiedades

finish_reason string

La razón por la que se detuvo la tarea. stop indica una finalización natural.

message object

El mensaje devuelto por el modelo.

Propiedades

role string

El rol del mensaje. Siempre assistant.

content array

Propiedades

type string

Valores: text, image.

text string

El texto generado.

imagen string

La URL de la imagen generada. Formato: PNG.

El enlace es válido por 24 horas. Descargue la imagen a la brevedad.

usage object

Estadísticas de uso para la solicitud. Solo se cuentan los resultados exitosos.

Propiedades

image_count integer

El número de imágenes generadas.

size string

La resolución de la imagen generada. Ejemplo: 1376*768.

input_tokens integer

El número de tokens de entrada (no facturable). La facturación se basa en el número de imágenes.

output_tokens integer

El número de tokens de salida (no facturable). La facturación se basa en el número de imágenes.

total_tokens integer

El número total de tokens (no facturable). La facturación se basa en el número de imágenes.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

SDK de Python

Los nombres de los parámetros del SDK son en gran medida consistentes con los de la API HTTP.

Las tareas de generación de imágenes pueden llevar tiempo, por lo que el SDK encapsula el flujo de trabajo asíncrono HTTP. Se admiten llamadas tanto síncronas como asíncronas.

La duración de la tarea depende de la longitud de la cola y del estado del servicio.

ImportanteAsegúrese de que su versión del SDK de Python de DashScope sea 1.25.15 o posterior. Para actualizar, consulte Instalar SDK.

Tanto base_url como la clave API son específicos de la región. El siguiente ejemplo utiliza la región Singapore:

Singapore

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

Al realizar la llamada, reemplace {WorkspaceId} con su ID de espacio de trabajo real.

China (Beijing)

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

Al realizar la llamada, reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Edición de imágenes

Llamada síncrona

Ejemplo de solicitud
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

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

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

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

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

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

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

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

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

La URL es válida durante 24 horas. Descargue la imagen oportunamente.

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

Llamada asíncrona

Ejemplo de solicitud
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# Main execution flow.
if __name__ == "__main__":
    task = create_async_task()
    wait_for_completion(task)
Ejemplo de respuesta
  1. Ejemplo de respuesta para crear una tarea
{
    "status_code": 200,
    "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": null,
        "audio": null,
        "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
        "task_status": "PENDING"
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0
    }
}
  1. Ejemplo de respuesta para consultar el resultado de una tarea

    La URL es válida durante 24 horas. Descargue la imagen oportunamente.

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

Generación de conjuntos de imágenes

Llamada síncrona

Ejemplo de solicitud
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

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

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

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

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

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

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

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

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

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

La URL es válida durante 24 horas. Descargue la imagen oportunamente.

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

Llamada asíncrona

Ejemplo de solicitud
import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

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

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

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

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

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

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

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

    # Submit an asynchronous task
    print("Submitting an asynchronous task...")
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        enable_sequential=True,
        n=4,
        size="2K",  # wan2.7-image-pro supports 4K resolution only in text-to-image scenarios. Image editing and image sequence generation support a maximum resolution of 2K.
    )

    if response.status_code == 200:
        print(f"Task submitted successfully. Task ID: {response.output.task_id}")

        # Wait for the task to complete
        status = ImageGeneration.wait(task=response, api_key=api_key)

        if status.output.task_status == "SUCCEEDED":
            print("Task completed!")
            # Extract the result image URLs and save them to a local device.
            for i, choice in enumerate(status.output.choices):
                for j, content in enumerate(choice["message"]["content"]):
                    if content.get("type") == "image":
                        image_url = content["image"]
                        file_name = f"output_{i}_{j}.png"
                        # The result URLs are valid for 24 hours. Download the images in a timely manner.
                        urllib.request.urlretrieve(image_url, file_name)
                        print(f"Image saved to {file_name}")
        else:
            print(f"Task failed. Status: {status.output.task_status}")
    else:
        print(f"Failed to create the task: {response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {e}")
Ejemplo de respuesta
  1. Ejemplo de respuesta para crear una tarea
{
    "status_code": 200,
    "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": null,
        "audio": null,
        "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
        "task_status": "PENDING"
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0
    }
}
  1. Ejemplo de respuesta para consultar el resultado de una tarea

    La URL es válida durante 24 horas. Descargue la imagen oportunamente.

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

SDK de Java

Los nombres de los parámetros del SDK son en gran medida consistentes con los de la API HTTP.

Las tareas de generación de imágenes pueden llevar tiempo, por lo que el SDK encapsula el flujo de trabajo asíncrono HTTP. Se admiten llamadas tanto síncronas como asíncronas.

ImportanteAsegúrese de que su versión del SDK de Java de DashScope sea 2.22.13 o posterior.

Singapore

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

Al realizar la llamada, reemplace {WorkspaceId} con su ID de espacio de trabajo real.

China (Beijing)

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

Al realizar la llamada, reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Edición de imágenes

Llamada síncrona

Ejemplo de solicitud
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

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

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

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

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

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

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

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

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

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

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

La URL es válida durante 24 horas. Guárdela oportunamente.

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

Llamada asíncrona

Ejemplo de solicitud
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

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

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

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

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

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

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

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

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

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

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

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

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Ejemplo de respuesta
  1. Ejemplo de respuesta para crear una tarea
{
    "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
    "output": {
        "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
        "task_status": "PENDING"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
  1. Ejemplo de respuesta para consultar el resultado de una tarea

    La URL es válida durante 24 horas. Guárdela oportunamente.

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

Generación de conjuntos de imágenes

Llamada síncrona

Ejemplo de solicitud
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

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

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

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

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

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

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

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

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

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

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

La URL es válida durante 24 horas. Guárdela oportunamente.

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

Llamada asíncrona

Ejemplo de solicitud
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

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

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

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

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

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

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

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

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

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

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

        // Wait for the task to complete.
        String taskId = taskResult.getOutput().getTaskId();
        ImageGenerationResult result = waitTask(taskId);
        // Fetch the resulting image URLs and save them to a local directory.
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Ejemplo de respuesta
  1. Ejemplo de respuesta para crear una tarea
{
    "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx",
    "output": {
        "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
        "task_status": "PENDING"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
  1. Ejemplo de respuesta para consultar el resultado de una tarea

    La URL es válida durante 24 horas. Guárdela oportunamente.

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

Facturación y limitación de tasa

  • Para la cuota gratuita y el precio unitario del modelo, consulte Precios de modelos.
  • Para la limitación de tasa del modelo, consulte Wanxiang.
  • Detalles de facturación: Se le factura según el número de imágenes generadas exitosamente. Las llamadas fallidas y los errores de procesamiento no generan cargos ni consumen su cuota gratuita para nuevos usuarios.

Códigos de error

Si la llamada al modelo falla y devuelve un mensaje de error, consulte Códigos de error para su resolución.