Image Stylization

Description

This API stylizes an input image according to a specified formula template. The formula ID is a dynamic business configuration. Contact your business representative to obtain the formula ID, then insert it into the task path.

Version

1.0

Image Requirements

  • Supported formats: JPG and PNG.

Request URL

    Production environment: https://openapi.meitu.com
    Task submission endpoint: https://openapi.meitu.com/api/v1/sdk/sync/push
    Task name (task): /v1/image_style/default/{formula_id}
    Task type (task_type): formula

{formula_id} is the formula ID component. It must be replaced with the actual formula ID provided by your business representative. This document does not provide a formula ID that can be called directly; requests containing {formula_id} cannot be submitted to the production endpoint.

HTTP Method

POST

Content-Type: application/json

Authentication

Open Platform API Signature

Request Parameters

RequiredParameterTypeDescription
YesparamsstringAlgorithm parameters encoded as a JSON string
Yesinit_imagesobject[]List of input images
YestaskstringDynamic path /v1/image_style/default/{formula_id}; replace {formula_id} with the formula ID provided by your business representative
Yestask_typestringFixed value: formula
Nosync_timeoutintDefault: 30; -1 means do not wait. If the synchronous wait times out, status 9 is returned and the result must be retrieved through the query API

Structure of each init_images item:

RequiredParameterTypeDescription
YesurlstringImage URL or base64 data
YesprofileobjectImage metadata

Structure of profile:

RequiredParameterTypeDescription
Yesmedia_profilesobjectMedia metadata
YesversionstringFixed value: v1

Structure of media_profiles:

RequiredParameterTypeDescription
Yesmedia_data_typestringurl indicates an image URL; jpg indicates base64-encoded JPG data

params is a JSON string with the following structure:

RequiredFieldTypeDescription
Norsp_media_typestringDefault: url; jpg returns the result image as base64 data, while url returns an image URL
YesparameterobjectCore algorithm parameters

parameter fields:

RequiredParameterTypeDescription
NopromptstringPositive prompt. Use (prompt:weight) to control text weight and <lora:model:weight> to configure a LoRA model and its weight. Available style models can be obtained through the related API. Example: girl,(cartoon:1.1),<lora:074594b2d60230282482d176d28c7c2e_1.0:0.8>
NoseedintRandom seed. Default: -1. A positive value produces relatively consistent content; -1 introduces random variation
NowidthintImage width. Default: 1024. Supported dimensions can be obtained through the related API
NoheightintImage height. Default: 1024. Supported dimensions can be obtained through the related API
Noresize_modeintResize mode: 1 for automatic scaling, 2 for stretching, and 3 for cropping. Default: cropping
Nonegative_promptstringNegative prompt
Noenable_image_face_detectboolWhether to enable face-detection interception
NostepsintNumber of sampling steps. Default: 50
Nodenoising_strengthfloat64Denoising strength. Range: [0,1]; step: 0.01; default: 0.8
Nocfg_scalefloat64Prompt guidance scale. Range: [1,20]; step: 0.5; default: 5
Noface_generation_scalefloat64Face similarity. Range: 0 to 1.0; default: 0.3. Pass a negative value, such as -1, to disable it
Nobatch_sizeintNumber of image-generation batches. Default: 1
Nosample_numintNumber of generated images. Default: 4; range: 1 to 4
Noadetailer_faceintFace restoration plug-in: 1 enables it and 2 disables it. Enabled by default

Request Example

Replace {formula_id} in the following example with the actual formula ID provided by your business representative.

{
  "task": "/v1/image_style/default/{formula_id}",
  "task_type": "formula",
  "init_images": [
    {
      "url": "https://example.com/input.jpg",
      "profile": {
        "media_profiles": {
          "media_data_type": "url"
        },
        "version": "v1"
      }
    }
  ],
  "params": "{\"rsp_media_type\":\"url\",\"parameter\":{\"prompt\":\"girl,(cartoon:1.1)\",\"seed\":-1,\"width\":1024,\"height\":1024,\"resize_mode\":3,\"negative_prompt\":\"\",\"enable_image_face_detect\":false,\"steps\":50,\"denoising_strength\":0.8,\"cfg_scale\":5,\"face_generation_scale\":0.3,\"batch_size\":1,\"sample_num\":4,\"adetailer_face\":1}}",
  "sync_timeout": 30
}

Response Fields

Note: Generated result images are periodically deleted. Download and save them promptly.

FieldTypeDescription
request_idstringRequest identifier
trace_idstringTrace identifier
codeintBusiness status code; 0 indicates that the request was accepted successfully
error_codeintError code; 0 on success
messagestringBusiness status message
tipsanyAdditional information; may be null
dataobjectTask status and algorithm result

data fields:

FieldTypeDescription
statusintTask status: -1 not found; 0 created; 1 processing; 2 failed; 9 timed out and must be retrieved through the query API; 10 succeeded
resultobjectAlgorithm result
progressnumberTask progress, for example 0.1, 0.85, or 1
predict_elapsedintEstimated processing time in milliseconds
create_timeint64Creation timestamp in milliseconds
task_idstringTask ID
custom_task_idstringClient-defined task ID
trace_idstringTrace identifier
client_infostringClient information
init_imagesobject[]/nullInput media echoed by the service

result fields:

FieldTypeDescription
idstringTask ID
urlsstring[]List of result image URLs

Response Examples

Successful Response

{
  "request_id": "req_1234567890",
  "trace_id": "trace_1234567890",
  "code": 0,
  "error_code": 0,
  "message": "success",
  "tips": null,
  "data": {
    "status": 10,
    "result": {
      "id": "50309bd5-a827-4125-bc96-62039c93770b",
      "urls": ["https://example.com/result.png"]
    },
    "progress": 1,
    "predict_elapsed": 0,
    "create_time": 1718172000000,
    "task_id": "50309bd5-a827-4125-bc96-62039c93770b",
    "custom_task_id": "",
    "trace_id": "trace_1234567890",
    "client_info": "",
    "init_images": null
  }
}

Query-Required Response

When status is 9, retrieve the result through the query API.

{
  "request_id": "req_1234567890",
  "trace_id": "trace_1234567890",
  "code": 0,
  "error_code": 0,
  "message": "success",
  "tips": null,
  "data": {
    "status": 9,
    "result": {
      "id": "task_1234567890"
    },
    "progress": 0,
    "predict_elapsed": 10000,
    "create_time": 1718172000000,
    "task_id": "task_1234567890",
    "custom_task_id": "",
    "trace_id": "trace_1234567890",
    "client_info": "",
    "init_images": null
  }
}

Failed Response

{
  "request_id": "req_1234567890",
  "trace_id": "trace_1234567890",
  "code": 20001,
  "error_code": 20001,
  "message": "PROCESS_ERROR",
  "tips": null,
  "data": {
    "status": 2,
    "result": {
      "id": "task_1234567890"
    },
    "progress": 0,
    "predict_elapsed": 0,
    "create_time": 1718172000000,
    "task_id": "task_1234567890",
    "custom_task_id": "",
    "trace_id": "trace_1234567890",
    "client_info": "",
    "init_images": null
  }
}

API-Specific Error Codes

Error CodeError MessageDescription
20001PROCESS_ERRORProcessing error

Common Error Codes

See API Error Codes.

SDK Examples

Before calling the API, set the formula ID variable in each SDK example to the actual value provided by your business representative.

Python

import json

import requests
from sign_sdk import sign

def api_call_example():
    key = "your_api_key"
    secret = "your_api_secret"
    formula_id = "your_formula_id"
    url = "https://openapi.meitu.com/api/v1/sdk/sync/push"
    method = "POST"

    headers = {
        "Content-Type": "application/json",
        sign.HeaderHost: "openapi.meitu.com",
    }
    inner_params = {
        "rsp_media_type": "url",
        "parameter": {
            "prompt": "girl,(cartoon:1.1)",
            "seed": -1,
            "width": 1024,
            "height": 1024,
            "resize_mode": 3,
            "negative_prompt": "",
            "enable_image_face_detect": False,
            "steps": 50,
            "denoising_strength": 0.8,
            "cfg_scale": 5,
            "face_generation_scale": 0.3,
            "batch_size": 1,
            "sample_num": 4,
            "adetailer_face": 1,
        },
    }
    payload = {
        "task": f"/v1/image_style/default/{formula_id}",
        "task_type": "formula",
        "init_images": [
            {
                "url": "https://example.com/input.jpg",
                "profile": {
                    "media_profiles": {"media_data_type": "url"},
                    "version": "v1",
                },
            }
        ],
        "params": json.dumps(inner_params, ensure_ascii=False),
        "sync_timeout": 30,
    }
    body = json.dumps(payload, ensure_ascii=False)

    signer = sign.Signer(key, secret)
    signed_request = signer.sign(url, method, headers, body)
    response = requests.Session().send(signed_request)
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")

if __name__ == "__main__":
    api_call_example()

Go

package main

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

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

func main() {
	key := "your_api_key"
	secret := "your_api_secret"
	formulaID := "your_formula_id"
	signObj := signer.NewSigner(key, secret)

	url := "https://openapi.meitu.com/api/v1/sdk/sync/push"
	method := http.MethodPost
	headers := make(http.Header)
	headers.Set(signer.HeaderHost, "openapi.meitu.com")
	headers.Set("Content-Type", "application/json")

	body := fmt.Sprintf(`{
  "task": "/v1/image_style/default/%s",
  "task_type": "formula",
  "init_images": [{
    "url": "https://example.com/input.jpg",
    "profile": {
      "media_profiles": {"media_data_type": "url"},
      "version": "v1"
    }
  }],
  "params": "{\"rsp_media_type\":\"url\",\"parameter\":{\"prompt\":\"girl,(cartoon:1.1)\",\"seed\":-1,\"width\":1024,\"height\":1024,\"resize_mode\":3,\"negative_prompt\":\"\",\"enable_image_face_detect\":false,\"steps\":50,\"denoising_strength\":0.8,\"cfg_scale\":5,\"face_generation_scale\":0.3,\"batch_size\":1,\"sample_num\":4,\"adetailer_face\":1}}",
  "sync_timeout": 30
}`, formulaID)

	req, err := signObj.Sign(url, method, headers, body)
	if err != nil {
		fmt.Println("Failed to sign request:", err)
		return
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Read response failed:", err)
		return
	}
	fmt.Println("Response:", resp.StatusCode, string(responseBody))
}

PHP

<?php
require 'signer.php';

$key = 'your_api_key';
$secret = 'your_api_secret';
$formulaId = 'your_formula_id';
$signer = new Signer($key, $secret);

$url = 'https://openapi.meitu.com/api/v1/sdk/sync/push';
$method = 'POST';
$headers = ['Content-Type' => 'application/json'];

$innerParams = json_encode([
    'rsp_media_type' => 'url',
    'parameter' => [
        'prompt' => 'girl,(cartoon:1.1)',
        'seed' => -1,
        'width' => 1024,
        'height' => 1024,
        'resize_mode' => 3,
        'negative_prompt' => '',
        'enable_image_face_detect' => false,
        'steps' => 50,
        'denoising_strength' => 0.8,
        'cfg_scale' => 5,
        'face_generation_scale' => 0.3,
        'batch_size' => 1,
        'sample_num' => 4,
        'adetailer_face' => 1,
    ],
]);

$body = json_encode([
    'task' => "/v1/image_style/default/{$formulaId}",
    'task_type' => 'formula',
    'init_images' => [
        [
            'url' => 'https://example.com/input.jpg',
            'profile' => [
                'media_profiles' => ['media_data_type' => 'url'],
                'version' => 'v1',
            ],
        ],
    ],
    'params' => $innerParams,
    'sync_timeout' => 30,
]);

$curl = $signer->sign($url, $method, $headers, $body);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status === 0) {
    echo 'Error: ' . curl_error($curl);
} else {
    echo "Status: {$status}\n";
    echo "Response: {$response}\n";
}
curl_close($curl);
?>

Java

package com.meitu.openai.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        Signer signer = new Signer("your_api_key", "your_api_secret");
        String formulaId = "your_formula_id";
        String url = "https://openapi.meitu.com/api/v1/sdk/sync/push";
        String method = "POST";

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put(Signer.HeaderHost, "openapi.meitu.com");

        String body = "{\n" +
                "  \"task\": \"/v1/image_style/default/" + formulaId + "\",\n" +
                "  \"task_type\": \"formula\",\n" +
                "  \"init_images\": [{\n" +
                "    \"url\": \"https://example.com/input.jpg\",\n" +
                "    \"profile\": {\n" +
                "      \"media_profiles\": {\"media_data_type\": \"url\"},\n" +
                "      \"version\": \"v1\"\n" +
                "    }\n" +
                "  }],\n" +
                "  \"params\": \"{\\\"rsp_media_type\\\":\\\"url\\\",\\\"parameter\\\":{\\\"prompt\\\":\\\"girl,(cartoon:1.1)\\\",\\\"seed\\\":-1,\\\"width\\\":1024,\\\"height\\\":1024,\\\"resize_mode\\\":3,\\\"negative_prompt\\\":\\\"\\\",\\\"enable_image_face_detect\\\":false,\\\"steps\\\":50,\\\"denoising_strength\\\":0.8,\\\"cfg_scale\\\":5,\\\"face_generation_scale\\\":0.3,\\\"batch_size\\\":1,\\\"sample_num\\\":4,\\\"adetailer_face\\\":1}}\",\n" +
                "  \"sync_timeout\": 30\n" +
                "}";

        Map<String, String> signedHeaders = signer.sign(url, method, headers, body);
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod(method);
        for (Map.Entry<String, String> entry : signedHeaders.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
        connection.setDoOutput(true);
        connection.getOutputStream().write(body.getBytes(StandardCharsets.UTF_8));

        int status = connection.getResponseCode();
        InputStream stream = status >= 400
                ? connection.getErrorStream()
                : connection.getInputStream();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            System.out.println("Response: " + status + " " + response);
        }
    }
}