Image outpainting

更新时间:
复制 MD 格式

Use the image outpainting model to adjust image sizes for specific layouts or to expand the view without cropping the main subject. The model supports several expansion methods:

  • Expand to a specified aspect ratio

  • Expand by a specified horizontal or vertical scale

  • Expand by a custom number of pixels on the top, bottom, left, and right

  • Rotate the image before expanding it

Important

This document applies only to the China (Beijing) region. Use an API key from this region.

Model and pricing

Model name

Unit price

Rate limit (shared between Alibaba Cloud accounts and RAM users)

Free quota(View)

QPS limit for task submission API

Number of concurrent tasks

image-out-painting

CNY 0.18/image

2

5

500 images

For more information about model throttling rules and FAQs, see Throttling.

Model Performance

Original image

image

Rotate and expand

(Rotate 90 degrees counterclockwise)

Proportional Graph Scaling

(1.5:1.5)

Expand by adding pixels

(Add pixels to the top, bottom, left, and right)

Expand by aspect ratio

(4:3)

image

image

Image extension result 1

image

For more examples, see More expansion examples.

Getting started

Prerequisites

Obtain and configure an API key and set it as an environment variable. The environment variable configuration is being deprecated and will be consolidated into the API key configuration.

Expansion recommendation: For a more natural result, keep the aspect ratio of the final output image close to 1:1. For example, expanding an image from 1000 × 1000 to 1500 × 1500 usually produces a better result than expanding it to 2000 × 1000.

Sample code

This model provides only an HTTP API. See the curl sample code.

Replace {WorkspaceId} with your actual workspace ID.

curl

Note

For a beginner's guide to making HTTP calls, see Postman.

Image generation takes time. The API uses an asynchronous mode. The call process has two steps:

Step 1: Create a task to get a task ID

The API returns a task ID. Use the task ID to query the image generation result.

Request sample

Rotate and expand

# The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.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' \
--data '{
    "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": {
        "angle": 90,
        "x_scale": 1.5,
        "y_scale": 1.5
    }
}'

Scale and expand

# The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.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' \
--data '{
    "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": {
        "x_scale": 1.5,
        "y_scale": 1.5
    }
}'

Expand by adding pixels in specified directions

# The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.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' \
--data-raw '{
    "model": "image-out-painting",
    "input": {
        "image_url": "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/7181881571/p826951.png"
    },
    "parameters": {
        "left_offset": 546,
        "right_offset": 960,
        "top_offset": 158,
        "bottom_offset": 939
    }
}'

Expand by a specified aspect ratio

# The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.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' \
--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":{
        "angle":0,
        "output_ratio":"4:3",
        "best_quality":false,
        "limit_image_size":true
    }
}'

Response sample

If the request is successful, the API returns a task ID. The task_id is valid for 24 hours.

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

Use the task_id from Step 1 to poll the task query API until the task_status is SUCCEEDED. After the task succeeds, the response contains the URL of the generated image.

Request sample

Replace 86ecf553-d340-4e21-xxxxxxxxx with your actual task_id.

If you use a model in the Singapore region, replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} is your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response sample

The image URL is valid for 24 hours. Download the image promptly.
{
    "request_id": "b67df059-ca6a-9d51-afcd-9b3c4456b1e2",
    "output": {
        "task_id": "d76ec1e8-ea27-4038-8913-235c88ef0f70",
        "task_status": "SUCCEEDED",
        "submit_time": "2024-05-16 13:50:01.247",
        "scheduled_time": "2024-05-16 13:50:01.354",
        "end_time": "2024-05-16 13:50:27.795",
        "output_image_url": "https://xxxx/xxxx"
    },
    "usage": {
        "image_count": 1
    }
}

Python

Note

Alibaba Cloud Model Studio does not provide an official Python software development kit (SDK) for image outpainting. The following sample code uses the `requests` library to make HTTP calls and is for reference only.

Environment configuration

  • Python 3.8 or later is recommended.

  • Install the required dependencies.

pip install -U requests

Sample request

import os
import requests
import time
from http import HTTPStatus

# Get the Alibaba Cloud Model Studio API key from an environment variable, or assign it directly in the code.
api_key = os.getenv("DASHSCOPE_API_KEY")
if not api_key:
    raise ValueError("Set the DASHSCOPE_API_KEY environment variable.")

# Replace with your Bailian workspace ID
workspace_id = "your-workspace-id"
# The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
base_url = f"https://{workspace_id}.cn-beijing.maas.aliyuncs.com"


def submit_task():
    """Submit an outpainting task."""
    url = f"{base_url}/api/v1/services/aigc/image2image/out-painting"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "X-DashScope-Async": "enable"  # Asynchronous invocation
    }

    body = {
        "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": {
            "angle": 90,
            "x_scale": 1.5,
            "y_scale": 1.5
        }
    }

    response = requests.post(url, headers=headers, json=body)

    if response.status_code == HTTPStatus.OK:
        task_id = response.json().get('output', {}).get('task_id')
        print(f"Task submitted successfully. Task ID: {task_id}")
        return task_id
    else:
        print(f"Task submission failed. Status code: {response.status_code}, Response: {response.text}")
        return None


def query_task_result(task_id):
    """Poll for the result based on the task ID."""
    if not task_id:
        return

    url = f"{base_url}/api/v1/tasks/{task_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    print("Querying task status...")
    while True:
        response = requests.get(url, headers=headers)
        if response.status_code != HTTPStatus.OK:
            print(f"Query failed. Status code: {response.status_code}, Response: {response.text}")
            break

        response_data = response.json()
        task_status = response_data.get('output', {}).get('task_status')

        if task_status == 'SUCCEEDED':
            print("Task completed successfully!")
            print(f"Successful task response data: {response_data}")
            url = response_data.get('output', {}).get('output_image_url', "")
            print(f"Generated image URL: {url}")
            break
        elif task_status == 'FAILED':
            print(f"Task failed. Error message: {response_data}")
            break
        else:
            print(f"Task is processing. Current status: {task_status}...")
            # This is a simple polling method. We recommend using a more robust polling mechanism in a production environment.
            time.sleep(5)  # Wait 5 seconds before the next query.


if __name__ == '__main__':
    task_id = submit_task()
    if task_id:
        query_task_result(task_id)

Sample response

Task submitted successfully. Task ID: 34d63d84-04c7-452e-88a4-ee76444d05e6
Querying task status...
Task is processing. Current status: RUNNING...
Task is processing. Current status: RUNNING...
Task completed successfully!
Successful task response data: {'request_id': 'ca5c1337-445e-9636-a46a-ba4b0cb39635', 'output': {'task_id': '34d63d84-04c7-452e-88a4-ee76444d05e6', 'task_status': 'SUCCEEDED', 'submit_time': '2025-09-02 16:51:12.386', 'scheduled_time': '2025-09-02 16:51:12.410', 'end_time': '2025-09-02 16:51:22.478', 'output_image_url': 'https://vigen-invi.oss-cn-shanghai.aliyuncs.com/xxx.jpg?xxxx'}, 'usage': {'image_count': 1}}
Generated image URL: https://vigen-invi.oss-cn-shanghai.aliyuncs.com/xxx.jpg?xxxx

More expansion examples

Expand by aspect ratio

Original image

Expanded image

Expansion parameters

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "output_ratio":"1:1"
    }
}

Expand by scale

Original image

Expanded image

Expansion parameters

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "x_scale": 2.46,
        "y_scale": 2.20
    }
}

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "x_scale": 1.86,
        "y_scale": 1.72
    }
}

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "x_scale": 2.39,
        "y_scale": 1.24
    }
}

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "x_scale": 1.41,
        "y_scale": 1.24
    }
}

Expand by adding pixels in specified directions

Original image

Expanded image

Expansion parameters

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "left_offset": 758,
        "right_offset": 968,
        "top_offset": 343,
        "bottom_offset": 539
    }
}

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "left_offset": 394,
        "right_offset": 879,
        "top_offset": 914,
        "bottom_offset": 709
    }
}

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "left_offset": 698,
        "right_offset": 420,
        "top_offset": 614,
        "bottom_offset": 643
    }
}

Rotate and expand

Original image

Expanded image

Expansion parameters

image

image

{
    "model": "image-out-painting",
    "parameters": {
        "angle": 45,
        "x_scale": 1.2,
        "y_scale": 1.2
    }
}

API reference

For more information about the input and response parameters of the image outpainting model, see Image Outpainting API.

Error codes

If the model call fails and returns an error message, see Error codes for resolution.

FAQ

Q: Why do I receive an error when I call the API?

A: Check the following items:

  • The API key is correct and configured in your environment variables or code.

  • The region of the API key matches the endpoint you are calling.

  • You can check if the free quota is exhausted.

  • The request parameters are correct. For example, check that the image_url is accessible from the public network. For local files, see Upload a file to obtain a temporary URL.

Q: Why does my task remain in the RUNNING state for a long time?

A: Image generation takes some time, typically within tens of seconds. If a task does not complete after a long time, the system might be busy. If the task is still not complete after several minutes, check the service status or contact technical support.