Image Inpainting

Updated at:
Document Overview

Use the Wanx model (wanx-x-painting) with an original image, a mask image, and a text prompt to generate new images quickly.

Important

  • This document applies only to the Chinese mainland (Beijing) region. You must use an API Key for this region.
  • The wanx-x-painting model currently offers a free trial. After you use up the free quota, you cannot invoke the model, and paid services are not supported. For alternative solutions, see Image Editing - Qwen or Image Editing - Wanx 2.1.

Overview

Wanx Image Inpainting is a post-processing pipeline for AI art generation based on the self-developed Composer composite generation framework. It generates diverse, semantically consistent inpainting results by combining user-provided original images, mask images, and text prompts. Using knowledge recombination and variable-dimension diffusion models, it accelerates convergence and improves output quality. The generated images feature natural layouts, rich details, refined visuals, and realistic outcomes.

Provide an original image and a mask image, then combine them with a modified prompt to generate new content within the masked area. Areas outside the mask remain unchanged.

Scenarios

  • Art Creation and Design: Artists and designers use image inpainting to iterate rapidly on creative works. For example, change a painting’s background, adjust clothing colors, or add new elements without starting from scratch. This significantly improves creative efficiency.
  • Education and Training: In art education, students use image inpainting to learn different painting techniques and styles. For example, modify parts of masterworks to understand color application, composition, and lighting.
  • Advertising and Marketing: The advertising industry uses image inpainting to quickly adapt product display images. For example, change product colors, background environments, or local scene elements to meet varying market and seasonal requirements. This increases advertising creativity and targeting flexibility.
  • Film and Game Production: In Post-production, image inpainting helps modify scene details efficiently. For example, adjust character costumes, prop styles, or optimize visual effects. This reduces the time and cost required to produce images, posters, and other materials.
  • Personalized Gift Customization: Image inpainting simplifies and accelerates personalized customization. For example, when adding personal photos to souvenirs, T-shirts, or cups, easily adjust backgrounds, blend artistic styles, or add custom text. This ensures professional-quality results that match personal preferences.

Features and Benefits

  • Knowledge Recombination and Variable-Dimension Diffusion Model: This AI local painting Large Language Model (LLM) is built on the self-developed Composer composite generation framework. It uses knowledge recombination and variable-dimension diffusion models to generate diverse image styles that match semantic descriptions.
  • Industry-Leading Results: Generated images exhibit precise semantic consistency. AI art creation delivers natural layouts, rich details, refined visuals, and realistic outcomes.
  • Highly Precise Semantic Control: You can precisely specify modification areas. This ensures generated content stays within the selected region while leaving the rest of the image unchanged. The result is high controllability and precision.
  • Easy Integration and Use: No advanced image editing skills are required. Simply describe your modification intent using a prompt. The Wanx series of generative Large Language Models (LLMs) handles complex image processing automatically, lowering the technical barrier.

Model Overview

ModelUnit priceRate limit (shared by Alibaba Cloud account and RAM users)

Free quota(View)

Request per second (RPS) for task submissionNumber of concurrent tasks

wanx-x-painting

For free trial only.

After the free quota is used up, you cannot invoke the model. For alternative solutions, see Image Editing - Qwen or Image Editing - Wanx 2.1.

2

1

500 images

QuickStart

Input image requirements:

  • Image format: JPG, JPEG, PNG, BMP, TIFF, or WEBP.
  • Image size: Up to 10 MB.
  • Image resolution: Greater than 256 × 256 pixels and less than 4096 × 4096 pixels.
  • The URL address must not contain Chinese characters. Obtain a temporary public network URL here.

Input Image (Before Inpainting)

Mask Image

Prompt Example

Output Image (After Inpainting)

image

image

a dog wearing red glasses

image

Because model computation takes a long time, all example code demonstrates asynchronous invocation methods to prevent request timeouts.

Obtain an API key and export the API key as an environment variable. If you use an SDK to make calls, install the DashScope SDK.

curl

1. Create a text-to-image task

Because model computation takes a long time, HTTP uses asynchronous invocation. Created tasks enter a task pool, awaiting scheduling and execution. Therefore, this API returns a task ID (task_id). Query the status and results later using this task ID.

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
  }
}'
2. Query text-to-image results by task ID
curl -X GET \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
https://dashscope.aliyuncs.com/api/v1/tasks/{your_task_id}

Python

from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "a dog wearing red glasses"
model = "wanx-x-painting"
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----')
try:
    job = client.images.generate(
        model=model,
        prompt=prompt,
        n=1,
        size='1024*1024',
        extra_input=extra_input)
    print(job.output)
    # save file to current directory
    for url in job.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "a dog wearing red glasses"
model = "wanx-x-painting"
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():
    job = client.images.jobs.create(
        model=model,
        prompt=prompt,
        n=1,
        size='1024*1024',
        extra_input=extra_input)
    print(job)
    print(job.task_id, job.status)
    return job

# 等待异步任务结束
def wait_async_task(job):
    done = client.images.jobs.wait(job)
    print(done)
    print(done.status)
    # save file to current directory
    for url in done.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)

if __name__ == '__main__':
    try:
        async_call()
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

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 Reference

For more information about API input and output parameters, see Wanx - Image Inpainting.