AI Image Expansion V2

Description

Use AI outpainting to generate content beyond the image borders based on the original image. Expand uniformly, specify a ratio or pixel count for each side, or expand automatically to a target aspect ratio.

Version

1.0

Image Requirements

JPG and PNG are supported.

Request URL

Production environment: https://openapi.meitu.com
Task submission endpoint: https://openapi.meitu.com/api/v1/sdk/sync/push
Task name (task): /v1/AI_Image_Expansion_v2/497076
Task type (task_type): formula

HTTP Method

POST

Content-Type: application/json

Authentication

Use Open Platform API Signing.

Request Parameters

RequiredParameterTypeDescription
YesparamsstringAlgorithm parameters encoded as a JSON string.
Yesinit_imagesobject[]Input image list. Submit one item.
Yestaskstring/v1/AI_Image_Expansion_v2/497076
Yestask_typestringformula
Nosync_timeoutintegerSet to -1 to submit without waiting for the result.

init_images

RequiredParameterTypeDescription
YesurlstringInput image URL.
—profileobjectImage media properties.

profile

RequiredParameterTypeDescription
—media_profilesobjectMedia type settings.
—versionstringExample value: v1.

media_profiles

RequiredParameterTypeDescription
—media_data_typestringUse url for an image URL.

params

The decoded params JSON contains the parameter object.

RequiredParameterTypeDescription
YesparameterobjectImage expansion settings.

parameter

RequiredParameterTypeDescription
Noexpand_rationumberUniform expansion ratio in [0, 1]. Default: 0.5. A value of 0.1 expands both dimensions to 120% of their original sizes; 0.5 expands both to 200%.
Nofree_expand_ratioobjectExpansion ratio for each side. Each value must be in [0, 1].
Nofree_expand_pixelobjectNumber of pixels to add on each side. Each value must be a non-negative integer.
NomodeintegerOmit to use manual expansion parameters. Use 1 to expand automatically according to ratio, or 2 to expand to 1:1 without specifying ratio.
ConditionalratiostringRequired when mode=1. Accepted values: arbitrary, 1:1, 3:4, 4:3, 9:16, and 16:9.
Nogenerate_numintegerNumber of images to generate. Default: 1; maximum: 20.
NoseedintegerRandom seed in [-1, 65535]. Default: 0. Use a fixed seed for reproducibility or -1 for a random seed.
Noextra_promptstringAdditional guidance for the generated content. Use English and separate multiple prompts with commas.
Nohigh_quality_encodebooleanEncode the result with less compression. Default: false. Enabling this can improve encoding quality and increase latency without changing the generated content.
Norsp_media_typestringUse url for result image URLs or jpg for Base64 image data.

For manual expansion, pass at most one of expand_ratio, free_expand_ratio, and free_expand_pixel. For per-side expansion, supply all four fields: top, bottom, left, and right. Use 0 for any side that should remain unchanged. Ratios for the top and bottom are relative to the original height; ratios for the left and right are relative to the original width. For example, top: 0.1 adds 10% of the original height above the image.

Request Example

This example adds 25% of the original dimension on each side.

{
  "task": "/v1/AI_Image_Expansion_v2/497076",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"parameter\":{\"rsp_media_type\":\"url\",\"free_expand_ratio\":{\"top\":0.25,\"bottom\":0.25,\"left\":0.25,\"right\":0.25},\"seed\":42,\"extra_prompt\":\"Extend the background and keep its color consistent.\"}}",
  "sync_timeout": -1
}

Response Fields

FieldTypeDescription
error_codeintegerError code. 0 indicates success.
messagestringProcessing message.
data.statusintegerTask status.
data.result.idstringTask ID used to query the task.
data.result.urlsstring[]Result image URLs returned on success.
data.progressnumberTask progress. 1 indicates completion.

Response Examples

Successful Response

Response Status: 200

Content-Type: application/json; charset=utf-8

{
  "error_code": 0,
  "message": "success",
  "data": {
    "status": 10,
    "result": {
      "id": "example-task-id",
      "urls": [
        "https://example.com/result.jpeg"
      ]
    },
    "progress": 1
  }
}

When to Query the Task

If data.status = 9, the synchronous wait timed out. This does not mean the task failed. Use data.result.id as the task ID in the Task Query API.

In the query response, 0 or 1 means the task is not complete, 10 means it succeeded, and 2 means it failed.

Failed Response

Response Status: 400

Content-Type: application/json; charset=utf-8

Common Error Codes

See API Error Codes.

SDK Examples

Before submitting a request, fill in your access key, secret key, and image URL.

Python

Python SDK

import requests
from sign_sdk import sign

url = "https://openapi.meitu.com/api/v1/sdk/sync/push"
body = r'''{
  "task": "/v1/AI_Image_Expansion_v2/497076",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"parameter\":{\"rsp_media_type\":\"url\",\"free_expand_ratio\":{\"top\":0.25,\"bottom\":0.25,\"left\":0.25,\"right\":0.25},\"seed\":42,\"extra_prompt\":\"Extend the background and keep its color consistent.\"}}",
  "sync_timeout": -1
}'''
headers = {"Content-Type": "application/json", sign.HeaderHost: "openapi.meitu.com"}

signer = sign.Signer("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
request = signer.sign(url, "POST", headers, body)
with requests.Session() as session:
    response = session.send(request, timeout=(10, 60), allow_redirects=False)
    print(response.status_code, response.text)

Go

Go SDK

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"time"

	"github.com/mtlab/api/signer"
)

func main() {
	url := "https://openapi.meitu.com/api/v1/sdk/sync/push"
	body := `{
  "task": "/v1/AI_Image_Expansion_v2/497076",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"parameter\":{\"rsp_media_type\":\"url\",\"free_expand_ratio\":{\"top\":0.25,\"bottom\":0.25,\"left\":0.25,\"right\":0.25},\"seed\":42,\"extra_prompt\":\"Extend the background and keep its color consistent.\"}}",
  "sync_timeout": -1
}`
	headers := make(http.Header)
	headers.Set(signer.HeaderHost, "openapi.meitu.com")
	headers.Set("Content-Type", "application/json")

	s := signer.NewSigner("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
	req, err := s.Sign(url, http.MethodPost, headers, body)
	if err != nil {
		log.Fatal(err)
	}
	client := &http.Client{
		Timeout: 60 * time.Second,
		CheckRedirect: func(*http.Request, []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	result, err := io.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.StatusCode, string(result))
}

PHP

PHP SDK

<?php
require_once __DIR__ . '/signer.php';

$url = 'https://openapi.meitu.com/api/v1/sdk/sync/push';
$body = <<<'JSON'
{
  "task": "/v1/AI_Image_Expansion_v2/497076",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"parameter\":{\"rsp_media_type\":\"url\",\"free_expand_ratio\":{\"top\":0.25,\"bottom\":0.25,\"left\":0.25,\"right\":0.25},\"seed\":42,\"extra_prompt\":\"Extend the background and keep its color consistent.\"}}",
  "sync_timeout": -1
}
JSON;
$headers = ['Host' => 'openapi.meitu.com', 'Content-Type' => 'application/json'];

$signer = new Signer('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');
$curl = $signer->sign($url, 'POST', $headers, $body);
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 60,
]);
$result = curl_exec($curl);
if ($result === false) {
    $error = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException($error);
}
echo curl_getinfo($curl, CURLINFO_HTTP_CODE), PHP_EOL, $result, PHP_EOL;
curl_close($curl);

Java

Java SDK

package com.meitu.openai.common;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://openapi.meitu.com/api/v1/sdk/sync/push";
        String body = "{\n" +
                "  \"task\": \"/v1/AI_Image_Expansion_v2/497076\",\n" +
                "  \"task_type\": \"formula\",\n" +
                "  \"init_images\": [\n" +
                "    {\n" +
                "      \"url\": \"https://example.com/input.jpg\",\n" +
                "      \"profile\": {\n" +
                "        \"media_profiles\": {\n" +
                "          \"media_data_type\": \"url\"\n" +
                "        },\n" +
                "        \"version\": \"v1\"\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"params\": \"{\\\"parameter\\\":{\\\"rsp_media_type\\\":\\\"url\\\",\\\"free_expand_ratio\\\":{\\\"top\\\":0.25,\\\"bottom\\\":0.25,\\\"left\\\":0.25,\\\"right\\\":0.25},\\\"seed\\\":42,\\\"extra_prompt\\\":\\\"Extend the background and keep its color consistent.\\\"}}\",\n" +
                "  \"sync_timeout\": -1\n" +
                "}";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put(Signer.HeaderHost, "openapi.meitu.com");

        Signer signer = new Signer("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY");
        Map<String, String> signed = signer.sign(url, "POST", headers, body);
        HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
        try {
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.setInstanceFollowRedirects(false);
            signed.forEach(connection::setRequestProperty);
            connection.setDoOutput(true);
            try (OutputStream out = connection.getOutputStream()) {
                out.write(body.getBytes(StandardCharsets.UTF_8));
            }
            int status = connection.getResponseCode();
            try (InputStream in = status >= 400 ? connection.getErrorStream() : connection.getInputStream()) {
                String result = in == null ? "" : new String(in.readAllBytes(), StandardCharsets.UTF_8);
                System.out.println(status + " " + result);
            }
        } finally {
            connection.disconnect();
        }
    }
}