文档

图像生成

更新时间:

图像生成模型利用人工智能技术,根据用户输入的文字描述自动生成高质量图像,并支持基于文字描述或参考图对已有图像进行修改和优化。

应用场景

  • 通用应用:涵盖图片美化、照片风格转换、人像摄影、证件照制作、抠图及个性化图像定制等场景。

  • 电商:商品图片生成、虚拟模特、AI试衣、背景替换及图像变换等。

  • 教育:生成创意教学内容、学术概念图解、教材、情景故事板、实验演示及文章插图等,提升课程互动性、直观性和创新性。

  • 广告设计:输入广告文案自动生成符合产品特性的视觉方案,并能根据消费者反馈,快速调整图像风格,以实现精准广告投放。应用于户外广告、电子广告、传单、海报及名片设计等。

  • 游戏设计:生成角色、道具及游戏环境等素材,加速游戏概念设计、场景风格设定、角色与道具开发等过程。

  • 环境与工业设计:基于文字描述或参考图像(如设计需求、色彩偏好、空间规划等),快速生成设计图,应用于室内、包装、陈列、封面、景观、服装及家居设计等领域。

示例场景1:服装设计

根据不同身形的试穿效果,通过图像局部重绘模型快速修改服装设计。

image

示例场景2:生成商品展拍图

通过虚拟模特生成模型在保持真人实拍模特站姿不变的前提下,对拍摄背景图、模特进行替换,快速生成更多模特拍摄图,加速服装内容创作。

image

图像生成模型

百炼支持通义万相系列的图像生成与编辑模型以及第三方Stable Diffusion、FLUX图像生成模型,详细的模型列表请参见图像生成模型

快速开始

通义万相是基于自研的Composer组合生成框架的AI图像生成模型,不同于传统扩散模型,Composer模型框架在加噪训练前,增加了对图像拆解和组合的过程。模型训练时会对图像中的物体蒙版、颜色、深度图、线条等信息进行拆分,并在生成阶段重新组合,因此模型具备高度可控性和极大自由度的图像生成效果。支持根据中英文输入生成图像、生成相似图、图像局部涂抹、图像风格和背景图替换、创意字生成、虚拟模特生成等功能。

基础文生图

功能:输入中英文任务描述,模型生成图像。

特点:支持生成水彩画、油画、中国画、素描、扁平插画、二次元、3D卡通、 摄影以及人像写真图像。

您可以指定图像分辨率size(1024*1024、720*1280、1280*720、768*1152)、生成图片数量n(1~4张)、图像风格style(sketch 素描、photography摄影、anime动漫、auto默认)。

模型名称

示例输入

示例输出

wanx-v1

提示词:少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光

cb28b5a1-2577-420e-9347-7b430bfa0c4f-1.png

说明

通过SDK使用基础文生图之前,需要先开通模型服务,然后创建API Key用于SDK调用时的身份认证。请务必妥善保管API Key,建议配置API Key为环境变量,避免明文写入代码中造成泄露。除SDK外,支持通过可视化界面快速、便捷地体验图像生成能力。

curl

请求示例
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
        "model": "wanx-v1",
        "input": {
            "prompt": "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光"
        },
        "parameters": {
            "style": "<auto>", 
            "size": "1024*1024",
            "n":1
        }
    }'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

Python

同步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = '少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光'


print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(model=ImageSynthesis.Models.wanx_v1,
                          prompt=prompt,
                          n=1,
                          style='<auto>',
                          size='1024*1024')
if rsp.status_code == HTTPStatus.OK:
    print(rsp.output)
    # save file to current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

异步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = '少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光'


def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# 创建异步任务
def create_async_task():
    rsp = ImageSynthesis.async_call(model=ImageSynthesis.Models.wanx_v1,
                                    prompt=prompt,
                                    n=1,
                                    style='<auto>',
                                    size='1024*1024')
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# 等待异步任务结束
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
        # save file to current directory
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()

Java

同步调用

import com.alibaba.dashscope.aigc.imagesynthesis.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void syncCall() {
        String prompt = "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }


    public static void main(String[] args){
        Main main = new Main();
        main.syncCall();
    }

}

异步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }


    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
        System.out.println(JsonUtils.toJson(result.getUsage()));
    }


    public static void main(String[] args){
        Main main = new Main();
        main.asyncCall();
    }

}

更多信息请参见API详情

生成相似图

输入参考图像和提示词,模型根据参考图像的颜色、笔触、风格以及提示词生成相似图。

模型名称

示例输入

示例输出

wanx-v1

玫瑰.png

参考图

提示词:玫瑰花海,背景是日出,采用淡紫色和粉红色的概念艺术装置风格,郁郁葱葱的风景,以及有序的布局

6e2a1f7f-177f-4d2a-bddd-e8ad48ab0d30-1.png

curl

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx-v1",
  "input": {
    "prompt": "玫瑰花海,背景是日出,采用淡紫色和粉红色的概念艺术装置风格,郁郁葱葱的风景,以及有序的布局",
    "ref_img": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/玫瑰.png"
  },
  "parameters": {
    "n": 1
  }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

Python

同步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = '少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光'
ref_img = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png"


print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(model=ImageSynthesis.Models.wanx_v1,
                          prompt=prompt,
                          n=1,
                          style='<auto>',
                          size='1024*1024',
                          ref_img=ref_img)
if rsp.status_code == HTTPStatus.OK:
    print(rsp.output)
    # save file to current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

异步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = '少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光'
ref_img = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png"


def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# 创建异步任务
def create_async_task():
    rsp = ImageSynthesis.async_call(model=ImageSynthesis.Models.wanx_v1,
                                    prompt=prompt,
                                    n=1,
                                    style='<auto>',
                                    size='1024*1024',
                                    ref_img=ref_img)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# 等待异步任务结束
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
        # save file to current directory
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()

Java

同步调用

package org.example.bailian.text2similarimage.sync;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void syncCall() {
        String prompt = "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光";
        String refImage = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.syncCall();
    }

}

异步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }


    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光";
        String refImage = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
        System.out.println(JsonUtils.toJson(result.getUsage()));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
         text2Image.asyncCall();

    }

}

更多信息请参见API详情

图像背景生成

功能:

  • 输入图像和任务描述,模型生成带有背景的图像。

  • 输入图像和参考背景图,模型生成带有背景的图像。

您可以通过scene_type指定图像的使用场景,默认值GENERAL为通用场景、ROOM室内家居场景、COSMETIC美妆场景,COSMETIC适用于大部分小商品摆放场景;通过noise_level设置生成图像与参考背景图的相似度,默认值300,取值范围[0,999],值越大相似度越低。

模型名称

示例输入

示例输出

wanx-background-generation-v2

a.png

原始图

d1faf4f26c8c4ea798d043a8bf3784bb_2.png

背景图

提示词:放在布满苔藓的土地上,被蕨类植物叶片包围,背景是茂盛的植被,丰富的光影细节

171852_0_f96add00-2a73-412c-a196-544ec58c74e9.png

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-background-generation-v2",
    "input": {
        "base_image_url": "https://vision-poster.oss-cn-shanghai.aliyuncs.com/lllcho.lc/data/test_data/images/main_images/new_main_img/a.png",
        "ref_image_url": "https://vision-poster.oss-cn-shanghai.aliyuncs.com/lllcho.lc/data/test_data/images/ref_images/d1faf4f26c8c4ea798d043a8bf3784bb_2.png",
        "ref_prompt": "放在布满苔藓的土地上,被蕨类植物叶片包围,背景是茂盛的植被,丰富的光影细节",
        "reference_edge": {
            "foreground_edge": [
                "https://vision-poster.oss-cn-shanghai.aliyuncs.com/lllcho.lc/data/test_data/images/huaban_soft_edge/6cdd13941cef1b11d885aea1717b983ae566b8efc9094-vcsvxa_fw658webp.png"
            ]
        }
    },
    "parameters": {
        "n":1,
        "noise_level": 300,
        "ref_prompt_weight": 0.5,
        "scene_type": "GENERAL"
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

涂鸦作画

功能:输入白色背景、黑色线条的手绘图和任务描述,模型基于手绘图的线条生成具备创意性和趣味性的涂鸦图像。

特点:支持生成扁平插画(flat illustration)、油画(oil painting)、二次元(anime)、3D卡通(3d cartoon)以及水彩(watercolor)五种风格的图像。

模型名称

示例输入

示例输出

wanx-sketch-to-image-lite

image

原始图

提示词:一颗参天大树

d33cc742-4e3e-4764-906c-de69036c8f1c-1.png

curl

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-sketch-to-image-lite",
    "input": {
        "sketch_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E6%B6%82%E9%B8%A6%E8%8D%89%E5%9B%BE.png",
        "prompt": "一棵参天大树"
    },
    "parameters": {
        "size": "768*768",
        "n": 2,
        "sketch_weight": 3,
        "style": "<watercolor>"
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

Python

同步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = "一棵参天大树"
sketch_image_url = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg"
model = "wanx-sketch-to-image-lite"
task = "image2image"


print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(model=model,
                          prompt=prompt,
                          n=1,
                          style='<watercolor>',
                          size='768*768',
                          sketch_image_url=sketch_image_url,
                          task=task)
if rsp.status_code == HTTPStatus.OK:
    print(rsp.output)
    # save file to current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

异步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = "一棵参天大树"
sketch_image_url = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg"
model = "wanx-sketch-to-image-lite"
task = "image2image"


# 异步调用
def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# 创建异步任务
def create_async_task():
    rsp = ImageSynthesis.async_call(model=model,
                                    prompt=prompt,
                                    n=1,
                                    style='<watercolor>',
                                    size='768*768',
                                    sketch_image_url=sketch_image_url,
                                    task=task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# 等待异步任务结束
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
        # save file to current directory
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()

Java

同步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void syncCall() {
        String prompt = "一棵参天大树";
        String sketchImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg";
        String model = "wanx-sketch-to-image-lite";
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .model(model)
                .prompt(prompt)
                .n(1)
                .size("768*768")
                .sketchImageUrl(sketchImageUrl)
                .style("<watercolor>")
                .build();

        String task = "image2image";
        ImageSynthesis imageSynthesis = new ImageSynthesis(task);
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.syncCall();
    }

}

异步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }

    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "一棵参天大树";
        String sketchImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg";
        String model = "wanx-sketch-to-image-lite";
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .model(model)
                .prompt(prompt)
                .n(1)
                .size("768*768")
                .sketchImageUrl(sketchImageUrl)
                .style("<watercolor>")
                .build();

        String task = "image2image";
        ImageSynthesis imageSynthesis = new ImageSynthesis(task);
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
        System.out.println(JsonUtils.toJson(result.getUsage()));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
         text2Image.asyncCall();
    }

}

更多信息请参见API详情

图像局部重绘

功能:输入图像、局部涂抹图以及任务描述,模型对图像进行局部重绘。

特点:可精确指定修改区域,生成的内容仅限于所选区域,图像其余部分保持不变。

模型名称

示例输入

示例输出

wanx-x-painting

image

原始图

image

指定局部涂抹图时,模型在原图中根据提示词只针对局部涂抹图重新绘制。

提示词:a dog wearing red glasses

3e89d278-5ddc-40c0-9b47-dffe37cb8ae9-1.png

curl

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx-x-painting",
  "input": {
    "prompt": "a dog wearing red glasses",
    "base_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/source3.jpg",
    "mask_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/glasses.png"
  },
  "parameters": {
    "size": "1024*1024",
    "n": 1
  }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

Python

同步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = "a dog wearing red glasses"
model = "wanx-x-painting"
task = "image2image"
extra_input = {
    "base_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/source3.jpg",
    "mask_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/glasses.png"
}


print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(model=model,
                          prompt=prompt,
                          n=1,
                          size='1024*1024',
                          task=task,
                          extra_input=extra_input)
if rsp.status_code == HTTPStatus.OK:
    print(rsp.output)
    # save file to current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

异步调用

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis

prompt = "a dog wearing red glasses"
model = "wanx-x-painting"
task = "image2image"
extra_input = {
    "base_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/source3.jpg",
    "mask_image_url": "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/glasses.png"
}


def async_call():
    print('----create task----')
    task_info = create_async_task()
    print('----wait task done then save image----')
    wait_async_task(task_info)


# 创建异步任务
def create_async_task():
    rsp = ImageSynthesis.async_call(model=model,
                                    prompt=prompt,
                                    n=1,
                                    size='1024*1024',
                                    task=task,
                                    extra_input=extra_input)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
    return rsp


# 等待异步任务结束
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
        # save file to current directory
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    async_call()

Java

同步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.HashMap;

public class Main {

    public void syncCall() {
        String task = "image2image";
        ImageSynthesis imageSynthesis = new ImageSynthesis(task);
        ImageSynthesisParam param = genImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    private ImageSynthesisParam genImageSynthesis(){
        HashMap<String,Object> extraInputMap = new HashMap<>();
        extraInputMap.put("base_image_url", "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/source3.jpg");
        extraInputMap.put("mask_image_url", "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/glasses.png");
        String prompt = "a dog wearing red glasses";
        String model = "wanx-x-painting";
        return ImageSynthesisParam.builder()
                .model(model)
                .prompt(prompt)
                .n(1)
                .size("1024*1024")
                .extraInputs(extraInputMap)
                .build();
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.syncCall();
    }

}

异步调用

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.HashMap;

public class Main {

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }


    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String task = "image2image";
        ImageSynthesis imageSynthesis = new ImageSynthesis(task);
        ImageSynthesisParam param = genImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    private ImageSynthesisParam genImageSynthesis(){
        String prompt = "a dog wearing red glasses";
        String model = "wanx-x-painting";
        HashMap<String,Object> extraInputMap = new HashMap<>();
        extraInputMap.put("base_image_url", "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/source3.jpg");
        extraInputMap.put("mask_image_url", "http://synthesis-source.oss-accelerate.aliyuncs.com/lingji/validation/mask2img/demo/glasses.png");

        return ImageSynthesisParam.builder()
                .model(model)
                .prompt(prompt)
                .n(1)
                .size("1024*1024")
                .extraInputs(extraInputMap)
                .build();
    }


    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
        System.out.println(JsonUtils.toJson(result.getUsage()));
    }


    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.asyncCall();
    }

}

更多信息请参见API详情

Cosplay动漫人物生成

功能:输入人像原图和卡通动漫形象参考图,模型生成人物3D卡通人物写真。

特点:专注动漫3D卡通人物形象生成,model_index取值固定为1,表示3D卡通形象。

模型名称

示例输入

示例输出

wanx-style-cosplay-v1

cosplay-原图-女.jpg风格参考图-裁剪.jpg

20240827161301902615_1_fhyb0o6a1z.jpg

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-style-cosplay-v1",
    "input": {
        "model_index": 1,
         "face_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/cosplay-%E5%8E%9F%E5%9B%BE-%E5%A5%B3.jpg",
        "template_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E9%A3%8E%E6%A0%BC%E5%8F%82%E8%80%83%E5%9B%BE-%E8%A3%81%E5%89%AA.jpg"
    }
 }'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

人像风格重绘

模型支持在保留人物面部轮廓和特征的前提下,对输入的人物图像进行风格重绘。

模型名称

示例输入

示例输出

wanx-style-repaint-v1

image

输入原始图、指定风格为复古漫画

20240815140946560032_style0_yjawdgq2bt.jpg

image

输入原图和风格参考图,上图为风格参考图

20240801144831232702_refstyle_om6dxjc71q.jpg

根据预置风格生成人像

选择系统预置风格生成人像:输入人像并选择预置人像风格,模型进行人像风格重绘。

通过style_index指定生成的人像风格:0复古漫画、1为3D童话、2为二次元风格、3小清新、4未来科技、5国画古风、6为将军百战风、7炫彩卡通、8清雅国风、9喜迎新年。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-style-repaint-v1",
    "input": {
        "image_url": "https://public-vigen-video.oss-cn-shanghai.aliyuncs.com/public/dashscope/test.png",
        "style_index": 0
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

根据自定义风格生成人像

输入人像和风格参考图,模型根据风格参考图重绘人像风格。

style_index赋值为-1,模型使用参考图重绘人像风格。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "wanx-style-repaint-v1",
    "input": {
        "image_url": "https://public-vigen-video.oss-cn-shanghai.aliyuncs.com/public/dashscope/test.png",
        "style_index": -1,
        "style_ref_url": "https://vigen-video.oss-cn-shanghai.aliyuncs.com/VideoGeneration/Data/cosplay%E8%A7%92%E8%89%B2%E5%BA%93/%E6%96%B0%E7%89%88%E9%9D%A2%E5%BD%A2%E8%B1%A1%E5%BA%93/ACG%E9%A3%8E%E6%A0%BC%EF%BC%88%E7%94%B7%EF%BC%89/65ba3ee96b1b868dfad0cf96c52c86112e035bb893329b8dda2a90b8a38485e0.png"
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

FaceChain人物写真生成

功能:

  • (推荐)人物形象免训练trainfree模式:输入一组包含人物正脸单人照(1~5张)和人像风格模板或者选择系统预置风格,模型生成人物写真照。

  • 人物形象训练lora模式:通过人物形象训练模型(facechain-finetune)对上传的人物图像进行模型训练,获得人物的resource,基于人物形象lora生成高保真人物形象写真。

模型名称

说明

示例输入

示例输出

facechain-facedetect

人物图像检测:

对上传的人物图像进行检测,判断图像人脸是否符合facechain微调标准。

image

风格:商务写真

image

facechain-finetune

人物形象训练:通过上传的人像压缩包进行模型训练,获得该对应人物的resource,基resource生成人物写真。

facechain-generation

人物写真生成

更多信息请参见API详情

虚拟模特生成

模型支持在保持真人实拍模特站姿不变的前提下,对拍摄背景图、模特进行替换,快速生成更多模特拍摄图。

模型名称

示例输入

示例输出

wanx-virtualmodel

真人模特实拍-女 (1).jpeg

"prompt":"一名年轻女子,身穿白色短裤,极简风格调色板,长镜头,双色效果,暗银色和浅粉色"

"face_prompt":"一名年轻女子,面容娇好,最好的品质"

虚拟模特结果1.png

virtualmodel-v2

image

任务描述:

"prompt":"A woman stands on a rural road"

"face_prompt":"good face, beautiful face, best quality."

"background_image_url":

image

image

根据真人实拍图和中英文描述生成图像

wanx-virtualmodel,输入真人模特实拍图和中英文任务描述,模型在保持人物站姿不变的前提下,生成展拍图。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx-virtualmodel",
  "input": {
    "base_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%9C%9F%E4%BA%BA%E6%A8%A1%E7%89%B9%E5%AE%9E%E6%8B%8D-%E5%A5%B3%20%281%29.jpeg",
    "mask_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/image.jpg",
    "prompt": "一名年轻女子,身穿白色短裤,极简风格调色板,长镜头,双色效果(暗银色和浅粉色)",
    "face_prompt": "年轻女子,面容姣好,最高品质"
  },
  "parameters": {
    "short_side_size": "512",
    "n": 2
  }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

根据真人实拍图和英文描述生成图像(推荐)

virtualmodel-v2,输入真人实拍图和英文任务描述,模型在保持人物站姿不变的前提下,重新生成展拍图。相较于wanx-virtualmodel,virtualmodel-v2对任务文字描述的理解更加准确。

base_image_url为原始图像地址,mask_image_url为对应原始图像期望生成图像中保留的区域,background_image_url为背景参考图地址。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "virtualmodel-v2",
  "input": {
    "base_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%9C%9F%E4%BA%BA%E6%A8%A1%E7%89%B9%E5%AE%9E%E6%8B%8D-%E5%A5%B3%20%281%29.jpeg",
    "mask_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/image.jpg",
    "prompt": "A woman stands on a rural road",
    "face_prompt": "good face, beautiful face, best quality.",
    "background_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E8%99%9A%E6%8B%9F%E6%A8%A1%E7%89%B9%E7%94%9F%E6%88%90%E8%83%8C%E6%99%AF%E5%9B%BE.png"
  },
  "parameters": {
      "short_side_size": "1024",
      "n": 1
  }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

鞋靴虚拟模特生成

输入脚部图(露出膝盖)template_image_url或者站立人像图(露出膝盖和脚部)以及多角度商品鞋靴图shoe_image_url,模型根据脚部布局和商品鞋靴生成鞋靴展拍图。

模型名称

示例输入

示例输出

shoemodel-v1

image

image

image

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "shoemodel-v1",
    "input": {
        "template_image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E9%9E%8B%E9%9D%B4%E5%9B%BE.webp",
        "shoe_image_url": ["https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E9%9E%8B%E9%9D%B4temp.webp"]
    },
    "parameters": {
        "n": 1
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

图像画面扩展

功能:输入图像并指定扩展系数(图像的宽度和高度)或者扩展像素,模型扩展图像画面。

输出图像比例越接近1:1,扩展效果越好。例如输入图像像素为1000x1000,输出图像像素设置为1500x1500的效果比2000x1000更好。

特点:只需指定图像扩展宽度、高度或者像素值,模型快速实现高保真画面扩展。

模型名称

示例输入

示例输出

image-out-painting

image

扩展系数:

parameters.left_offset=546

parameters.right_offset=960

parameters.top_offset=158

parameters.bottom_offset=939

图像画面扩展结果1.jpg

请求示例
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-DataInspection: enable' \
--data-raw '{
    "model": "image-out-painting",
    "input": {
        "image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E5%9B%BE%E5%83%8F%E7%94%BB%E9%9D%A2%E6%89%A9%E5%B1%95.png"
    },
    "parameters": {
        "left_offset": 546,
        "right_offset": 960,
        "top_offset": 158,
        "bottom_offset": 939
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

人物实例分割

输入人物图像,模型识别出图像中的不同人物对象并画出每个对象边界的像素级掩码。

模型名称

示例输入

示例输出

image-instance-segmentation

image

image

输出结果1:像素级掩码图像

image

输出结果2:可视化图像

请求示例
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
    "model": "image-instance-segmentation",
    "input": {
            "image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E4%BA%BA%E5%83%8F%E5%88%86%E5%89%B2.png"
        },
    "parameters":{
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  https://dashscope.aliyuncs.com/api/v1/tasks/13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "ec8b3026-a647-44d4-96ca-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-09-04 09:56:35.885",
  "scheduled_time": "2024-09-04 09:56:35.904",
  "end_time": "2024-09-04 09:56:38.773",
  "output_image_url": "https://vigen-invi.oss-cn-shanghai.aliyuncs.com/service_dashscope/ImageInstanceSegmentation/2024-09-04/public/a18142e9-4f41-4848-89ed-551e19a3fb6b/mask-4d2b51ff-36cf-41ed-ad91-81e513ba6d9a.png?OSSAccessKeyId=LTAI5t7aiMEUzu1F2xPM****&Expires=1725418598&Signature=KMIJF1YV98wngEARr03UXSDGOPY%3D",
  "output_vis_image_url": "https://vigen-invi.oss-cn-shanghai.aliyuncs.com/service_dashscope/ImageInstanceSegmentation/2024-09-04/public/a18142e9-4f41-4848-89ed-551e19a3fb6b/vis_mask-7d8e566f-0282-4c87-8885-767306c405b5.png?OSSAccessKeyId=LTAI5t7aiMEUzu1F2xPM****&Expires=1725418598&Signature=VM75fxUgvypxPIx%2FFfAUqWcJkLE%3D",
  "usage": {
    "image_count": 1
  }
}

以下代码示例将得到的人物实例分割结果图拆分成擦除区域图以及保留区域图,后续调用图像擦除模型擦除不需要的人像。

原图

人物实例分割结果

保留区域

擦除区域

图片擦除2-原图.png

image

mask.png

图片擦除2-保留.png

reserve.png

图片擦除2-擦除.png

remove.png

import cv2
import numpy as np

def get_remove_mask(mask_path, remove_mask_path, reserve_ids=[]):
    mask = cv2.imread(mask_path)
    instance_num = int(mask.max())
    new_mask = np.zeros((mask.shape[0], mask.shape[1], 3))
    for i in range(1, instance_num+1):
        if i in reserve_ids:
            continue
        new_mask[mask[:, :, 0] == i] = (255, 255, 255)
    cv2.imwrite(remove_mask_path, new_mask.astype(np.uint8))


def get_reserve_mask(mask_path, reserve_mask_path, reserve_ids=[]):
    mask = cv2.imread(mask_path)
    instance_num = int(mask.max())
    new_mask = np.zeros((mask.shape[0], mask.shape[1], 3))
    for i in range(1, instance_num + 1):
        if i in reserve_ids:
            new_mask[mask[:,:,0] == i]  = (255, 255, 255)
    cv2.imwrite(reserve_mask_path, new_mask.astype(np.uint8))


if __name__ == '__main__':
    mask_path = 'mask.png'
    remove_mask_path = 'remove.png'
    reserve_mask_path = 'reserve.png'
    get_remove_mask(mask_path, remove_mask_path, reserve_ids=[1])
    get_reserve_mask(mask_path, reserve_mask_path, reserve_ids=[1])
    

更多信息请参见API详情

图像擦除补全

输入原图、待擦除区域掩码图像以及保留区域掩码图像,模型在保留原图背景的同时擦除指定图像区域。

针对人物图像的擦除补全,推荐通过人物实例分割模型得到需保留人物对象的图像掩码以及待擦除区域图像掩码。

为获得更好的图像效果,保留区域图像掩码图应确保干净、不含任何待擦除对象。当通过人物分割实例获取掩码图时,可设置parameters.dilate_flag=true对掩码区域做膨胀,规避涂抹区域边缘遗漏,得到清晰完整的掩码图。

模型名称

示例输入

示例输出

image-erase-completion

图片擦除2-原图.png

原图

图片擦除2-擦除.png

待擦除区域

图片擦除2-保留.png

保留区域

image

请求示例
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-DataInspection: enable' \
--data-raw '{
    "model": "image-erase-completion",
    "input": {
            "image_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E5%9B%BE%E7%89%87%E6%93%A6%E9%99%A42-%E5%8E%9F%E5%9B%BE.png",
            "mask_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E5%9B%BE%E7%89%87%E6%93%A6%E9%99%A42-%E6%93%A6%E9%99%A4.png",
            "foreground_url": "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E5%9B%BE%E7%89%87%E6%93%A6%E9%99%A42-%E4%BF%9D%E7%95%99.png"
        },
    "parameters":{
        "dilate_flag":true
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

创意海报生成

输入海报主标题title、副标题sub_title、正文body_text、中文提示词prompt_text_zh或者英文提示词prompt_text_en,选择海报风格lora_name(2D插画、浩瀚星云、透明玻璃、中国水墨、中国刺绣、浓郁色彩等)并设置海报风格权重lora_weight(权重值越接近1,风格越明显),模型生成创意海报。

说明
  • title、sub_title不超过30个字符。

  • body_text不超过50个字符。

  • 支持同时输入中英文提示词prompt_text_zh、prompt_text_en,总长度不超过50个字符或者单词。

模型名称

示例输入

示例输出

wanx-poster-generation-v1

"title":"春节快乐",

"sub_title":"家庭团聚,共享天伦之乐",

"body_text":"春节是中国最重要的传统节日之一,它象征着新的开始和希望",

"prompt_text_zh":"灯笼,小猫,梅花",

"wh_ratios":"竖版",

"lora_name":"童话油画",

"lora_weight":0.8,

"ctrl_ratio":0.7,

"ctrl_step": 0.7,

"generate_mode":"generate",

"generate_num":1

jianguo.wjg_通用海报专项_results_cache_dashscope_2024-08-01_2024-08-01-07-38-57_66f607dc-dc0b-4f06-a306-2e880b7826d8_0.render (1).png

"title":"抽象艺术家",

"sub_title":"有趣的灵魂终要相遇",

"body_text":"创意海报生成,自由设计,瞬间点亮创意生活",

"prompt_text_en":"master piece, high quality, futuristic city, streamlined, neon, light blue and light purple, glass texture",

"wh_ratios":"竖版",

"lora_name":"浅蓝抽象",

"lora_weight":0.8,

"ctrl_ratio":0.6,

"ctrl_step": 0.6,

"generate_mode":"generate",

jianguo.wjg_通用海报专项_results_cache_dashscope_2024-08-01_2024-08-01-08-26-40_eb531b50-e161-4b3f-a48a-01f6b5c45fbd_0.render.png

请求示例
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data-raw '{
    "model": "wanx-poster-generation-v1",
    "input": {
        "title": "春节快乐",
        "sub_title": "家庭团聚,共享天伦之乐",
        "body_text": "春节是中国最重要的传统节日之一,它象征着新的开始和希望",
        "prompt_text_zh": "灯笼,小猫,梅花",
        "wh_ratios": "竖版",
        "lora_name": "童话油画",
        "lora_weight": 0.8,
        "ctrl_ratio": 0.7,
        "ctrl_step": 0.7,
        "generate_mode": "generate",
        "generate_num": 1
    },
    "parameters": {}
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

WordArt锦书-创意文字生成

模型名称

说明

示例输入

示例输出

wordart-texture

文字纹理生成

image

提示词:精美玉石

风格类型:立体材质

image

wordart-semantic

文字变形

文字:桂林山水

提示词:山峦叠嶂、漓江蜿蜒、岩石奇秀

image

wordart-surnames

百家姓生成

百家姓:赵

提示词:中国水墨画,古代建筑,石阶,花

20240814_110533_seed-56989_000_1207025a-59ea-11ef-b2e9-00163e3b023f.jpg

文字纹理生成

输入文字图image.image_url(图为黑底白字)、文字内容text.text_content(支持中英文、阿拉伯数字,长度不超过6个字符),选择系统预置文字风格texture_style并输入效果提示词prompt,模型为文字添加纹理效果。

texture_style常见取值material立体材质、scene场景融合、lighting光影特效、marble大理石、mountain_lake湖光山色等。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/wordart/texture' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
     "model": "wordart-texture",
     "input": {
         "text": {
             "text_content": "艺术字",
             "font_name": "dongfangdakai",
             "output_image_ratio": "16:9"
         },
         "prompt": "精美玉石",
         "texture_style": "material"
     },
     "parameters": {
         "image_short_size": 704,
         "n": 1,
         "alpha_channel": false
     }
 }'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

文字变形

根据提示词内容,对输入的图片文字边缘轮廓进行创意变形,返回带有文字内容的黑底白色蒙版图。

请求示例
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/wordart/semantic' \
--header 'X-DashScope-Async: enable' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data-raw '{
    "model": "wordart-semantic",
    "input": {
        "text": "桂林山水",
        "prompt": "山峦叠嶂、漓江蜿蜒、岩石奇秀"
    },
    "parameters": {
        "n": 1
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

百家姓创意设计

根据提示词和风格引导图对文字进行创意设计,通过surname输入百家姓。

请求示例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/wordart/surnames' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
    "model": "wordart-surnames",
    "input":{
        "text": {
            "font_name": "gufeng3"
        },
        "surname": "赵",
        "prompt": "中国水墨画,古代建筑,石阶,花"
    }
}'
返回示例

请求可正常执行时,返回以下示例,任务正在排队中:

{
  "output": {
    "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
    "task_status": "PENDING"
  },
  "request_id": "7574ee8f-38a3-4b1e-9280-xxxxxxxxxxxx"
}

task_status为任务状态:

  • PENDING:任务排队中

  • RUNNING:任务处理中

  • SUSPENDED:任务挂起

  • SUCCEEDED:任务执行成功

  • FAILED:任务执行失败

获取任务执行状态

任务是异步执行,通过以下示例获取任务状态,将task_id替换为您自己的task_id(示例中task_id为13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx)。

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id} \
     -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
获取生成图像

当task_status为SUCCEEDED时,返回生成图像的URL以及任务执行结果信息:

{
  "task_id": "13b1848b-5493-4c0e-8c44-xxxxxxxxxxxx",
  "task_status": "SUCCEEDED",
  "submit_time": "2024-08-19 20:01:35.371",
  "scheduled_time": "2024-08-19 20:01:35.394",
  "end_time": "2024-08-19 20:01:40.594",
  "results": [
    {
      "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240819/200139_0_v2_35cf08f9-a64f-4cc0-b917-fa3b743841fb.png?Expires=1724155300&OSSAccessKeyId=LTAIxxx8qL&Signature=mSNP255ZrVzjUYrQJWTOoFhB2Yg%3D"
    }
  ],
  "task_metrics": {
    "TOTAL": 1,
    "SUCCEEDED": 1,
    "FAILED": 0
  },
  "usage": {
    "image_count": 1
  }
}

更多信息请参见API详情

Stable Diffusion

Stable Diffusion模型是由Stability AI推出的AI绘画模型,能够通过文本描述生成图像以及根据描述修改图像。Stable Diffusion模型经过大量高质量图像训练,生成的图像具有较高的逼真度和细节表现力。

请求示例
Python
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope

model = "stable-diffusion-xl"
prompt = "Eagle flying freely in the blue sky and white clouds"


def simple_call():
    rsp = dashscope.ImageSynthesis.call(model=model,
                                        prompt=prompt,
                                        negative_prompt="garfield",
                                        n=1,
                                        size='1024*1024')
    if rsp.status_code == HTTPStatus.OK:
        print(rsp)
        # 下载文件到当前文件夹
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    simple_call() 
Java
// Copyright (c) Alibaba, Inc. and its affiliates.
// 请添加okhttp依赖

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Main {
    private static final OkHttpClient CLIENT = new OkHttpClient();
    private static final String MODEL = "stable-diffusion-xl";
    private static final String PROMPT = "Eagle flying freely in the blue sky and white clouds";
    private static final String SIZE = "1024*1024";

    public static void basicCall() throws ApiException, NoApiKeyException, IOException {
        ImageSynthesis is = new ImageSynthesis();
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(Main.MODEL)
                        .n(1)
                        .size(Main.SIZE)
                        .prompt(Main.PROMPT)
                        .negativePrompt("garfield")
                        .build();

        ImageSynthesisResult result = is.call(param);
        System.out.println(JsonUtils.toJson(result));
        // 保存图片到本地
        for(Map<String, String> item :result.getOutput().getResults()){
            String paths = new URL(item.get("url")).getPath();
            String[] parts = paths.split("/");
            String fileName = parts[parts.length-1];
            Request request = new Request.Builder()
                    .url(item.get("url"))
                    .build();

            try (Response response = CLIENT.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                Path file = Paths.get(fileName);
                Files.write(file, response.body().bytes());
            }

        }
    }

    public static void main(String[] args){
        try{
            basicCall();
        }catch(ApiException|NoApiKeyException | IOException e){
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
返回示例
{
    "status_code": 200,
    "request_id": "08327623-c671-92ff-bdd7-1a2a87f40589",
    "code": null,
    "message": "",
    "output": {
        "task_id": "80e3e478-b276-4b68-a328-628982abd40d",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "example_url"
            }
        ],
        "submit_time": "2024-06-14 11:46:18.604",
        "scheduled_time": "2024-06-14 11:46:18.621",
        "end_time": "2024-06-14 11:46:36.043",
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

更多信息请参见API详情

FLUX

FLUX模型是由Black Forest Labs开源的高质量文本到图像生成模型,尤其擅长生成包含文字、多主体、手部细节的图片。

请求示例

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope

model = "flux-schnell"
prompt = "Eagle flying freely in the blue sky and white clouds"
prompt_cn = "一只飞翔在蓝天白云的鹰" # Prompt支持中英文


def simple_call(input_prompt):
    rsp = dashscope.ImageSynthesis.call(model=model,
                                        prompt=input_prompt,
                                        size='1024*1024')
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
        print(rsp.usage)
        # 保存到当前目录
        for result in rsp.output.results:
            file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(result.url).content)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    simple_call(prompt)
    simple_call(prompt_cn)
// Copyright (c) Alibaba, Inc. and its affiliates.

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Main {
  private static final OkHttpClient CLIENT = new OkHttpClient();
  private static final String MODEL = "flux-schnell";
  private static final String PROMPT = "Eagle flying freely in the blue sky and white clouds";
  private static final String PROMPT_CN = "一只飞翔在蓝天白云的鹰"
  private static final String SIZE = "1024*1024";

  public static void basicCall() throws ApiException, NoApiKeyException, IOException {
    ImageSynthesis is = new ImageSynthesis();
    ImageSynthesisParam param =
        ImageSynthesisParam.builder()
            .model(Main.MODEL)
            .n(1)
            .size(Main.SIZE)
            .prompt(Main.PROMPT)
            .negativePrompt("garfield")
            .build();

    ImageSynthesisResult result = is.call(param);
    System.out.println(result);
    // save image to local files.
    for(Map<String, String> item :result.getOutput().getResults()){
      String paths = new URL(item.get("url")).getPath();
      String[] parts = paths.split("/");
      String fileName = parts[parts.length-1];
      Request request = new Request.Builder()
        .url(item.get("url"))
        .build();

      try (Response response = CLIENT.newCall(request).execute()) {
        if (!response.isSuccessful()) {
          throw new IOException("Unexpected code " + response);
        }

        Path file = Paths.get(fileName);
        Files.write(file, response.body().bytes());
      }
      
    }
  }

  public void fetchTask() throws ApiException, NoApiKeyException {
    String taskId = "your task id";
    ImageSynthesis is = new ImageSynthesis();
    // If set DASHSCOPE_API_KEY environment variable, apiKey can null.
    ImageSynthesisResult result = is.fetch(taskId, null);
    System.out.println(result.getOutput());
    System.out.println(result.getUsage());
  }

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

返回示例

{
    "status_code": 200,
    "request_id": "ea8bfe77-2f35-9df3-ba47-7e05e917b3df",
    "code": null,
    "message": "",
    "output": {
        "task_id": "dea97660-9651-4e6b-a9c3-8afb325b28d0",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "url1"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

更多信息请参见API详情