1.接口说明

高级自动去水印 / 图片修复 API:在无需手动绘制蒙版的情况下,对输入图片进行自动检测和修复,可用于去除水印、文字、马赛克、遮挡物、电商图违规词或其他损坏区域,输出修复完成后的图片。

1.1 主要功能

高级自动修复:
自动检测需要清理的区域并填补缺损内容,生成自然连贯的纹理和背景。
同步/异步处理:
支持 sync 同步返回结果,也支持 async_submit 提交任务后通过 async_fetch 轮询结果。
提示词控制:
可通过 prompt 描述需要去除或修复的内容,例如水印、文字、遮挡物或电商图违规词。
任务状态查询:
异步任务会返回 image_id,可用于查询 addedprocessingdoneerror 等状态。

1.2 接入场景

商品图违规词清理、营销素材去水印、图片文字清理、老照片修复、图片瑕疵修补、内容编辑等。

2.请求信息

2.1 请求地址(URL)

POST http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1

2.2 请求方式

POST

2.3 请求头(header)

参数 类型 说明
Content-Type string application/json
APIKEY string 您的 API KEY 获取

2.4 请求体(body)

参数 是否必填 类型 说明
mode string 任务提交模式,sync 表示同步,async_submit 表示异步提交任务,默认为同步
image_base64 必填其中之一 string base64 编码的图片文件,图片文件小于 20M
image_url string 图片文件 url,图片文件小于 20M
prompt string 图片去水印/图片修复提示词
异步获取结果
mode string async_fetch
image_id string 异步提交任务返回的 image_id

2.5 请求示例

// 同步请求
{
  "image_base64": "图片base64编码",
  "mode": "sync",
  "prompt": "去除图片中的水印和遮挡文字"
}

// 异步提交任务
{
  "image_url": "https://example.com/demo.jpg",
  "mode": "async_submit",
  "prompt": "去除图片中的水印"
}

// 异步获取结果
{
  "mode": "async_fetch",
  "image_id": "异步提交任务返回的image_id"
}

3.返回信息

3.1 返回类型

JSON

3.2 返回字段说明

参数 类型 说明
code int 错误码
msg string 错误信息(英文)
msg_cn string 错误信息(中文)
image_id string 图片id
同步模式
result_base64 string 结果的base64编码,当code==0时会有该返回值
异步模式
status string 任务状态,added:已加入,processing:正在处理,done:处理完成,error:错误
wait_time float 大概还需等待时间(秒), ex: 12.3
result_base64 string 结果的base64编码,当status为 done 时有该返回值

3.3 返回示例

// 同步成功示例
{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "b6a0f7d0b2f54d0ea3...",
  "result_base64": "/9j/4AAQSkZJRgABAQAAAQABAAD..."
}

// 异步提交成功示例
{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "b6a0f7d0b2f54d0ea3...",
  "status": "added",
  "wait_time": 12.3
}

// 异步获取结果成功示例
{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "b6a0f7d0b2f54d0ea3...",
  "status": "done",
  "result_base64": "/9j/4AAQSkZJRgABAQAAAQABAAD..."
}

// 失败示例
{
  "code": 4,
  "msg": "Invalid parameter",
  "msg_cn": "参数错误"
}

3.4 错误码说明

错误码 说明
0 成功
1 图片错误
2 处理错误
3 服务器繁忙
4 参数错误,具体错误请查看 msgmsg_cn
5 未知错误
101 API-KEY 不正确
102 未知用户
103 积分已用完
104 扣除积分失败

4.示例代码

4.1 Python 示例

# -*- coding: utf-8 -*-
import requests
import base64
import cv2
import json
import numpy as np

api_key = '******'  # 你的API KEY
image_path = '...'  # 图片路径

"""
同步请求:mode 为 sync,直接返回 result_base64。
"""
with open(image_path, 'rb') as fp:
    image_base64 = base64.b64encode(fp.read()).decode('utf8')

url = 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1'
headers = {'APIKEY': api_key, "Content-Type": "application/json"}
data = {
    "image_base64": image_base64,
    "mode": "sync",
    "prompt": "去除图片中的水印和遮挡文字"
}

response = requests.post(url=url, headers=headers, json=data)
response = json.loads(response.content)
"""
成功:{'code': 0, 'msg': 'OK', 'msg_cn': '成功', 'result_base64': result_base64, 'image_id': image_id}
or
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息}
"""
image_id = response['image_id']
result_base64 = response['result_base64']
file_bytes = base64.b64decode(result_base64)
f = open('result.jpg', 'wb')
f.write(file_bytes)
f.close()

image = np.asarray(bytearray(file_bytes), dtype=np.uint8)
image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED)
cv2.imshow('result', image)
cv2.waitKey(0)

"""
异步请求:先 async_submit 提交任务,再用 async_fetch 获取结果。
"""
submit_data = {
    "image_base64": image_base64,
    "mode": "async_submit",
    "prompt": "去除图片中的水印"
}
submit_resp = requests.post(url=url, headers=headers, json=submit_data)
submit_resp = json.loads(submit_resp.content)
image_id = submit_resp["image_id"]

fetch_data = {
    "mode": "async_fetch",
    "image_id": image_id
}
fetch_resp = requests.post(url=url, headers=headers, json=fetch_data)
fetch_resp = json.loads(fetch_resp.content)
print(fetch_resp)

4.2 PHP 示例

$url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1";
$method = "POST";
$apikey = "******";
$header = array();
array_push($header, "APIKEY:" . $apikey);
array_push($header, "Content-Type:application/json");

$image_path = "...";
$handle = fopen($image_path, "r");
$image = fread($handle, filesize($image_path));
fclose($handle);
$image_base64 = base64_encode($image);

$data = array(
  "image_base64"=> $image_base64,
  "mode"=> "sync",
  "prompt"=> "去除图片中的水印和遮挡文字"
);
$post_data = json_encode($data);

$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($curl);
var_dump($response);

4.3 Java

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;
import org.json.JSONObject;

public class AutoInpaintApiExample {
    public static void main(String[] args) {
        String apiKey = "******";
        String filePath = "...";
        String apiUrl = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1";

        try {
            String imageBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(new File(filePath).toPath()));
            JSONObject requestData = new JSONObject();
            requestData.put("image_base64", imageBase64);
            requestData.put("mode", "sync");
            requestData.put("prompt", "去除图片中的水印和遮挡文字");

            JSONObject response = sendPost(apiUrl, apiKey, requestData);
            if (response.getInt("code") == 0) {
                byte[] resultBytes = Base64.getDecoder().decode(response.getString("result_base64"));
                Files.write(new File("result.jpg").toPath(), resultBytes);
                System.out.println("自动去水印成功,已保存 result.jpg");
            } else {
                System.out.println("请求失败: " + response.optString("msg_cn", response.optString("msg")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static JSONObject sendPost(String apiUrl, String apiKey, JSONObject body) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("APIKEY", apiKey);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.toString().getBytes("utf-8"));
        }
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String line;
            while ((line = br.readLine()) != null) sb.append(line.trim());
        }
        return new JSONObject(sb.toString());
    }
}

4.4 JavaScript 示例

const fs = require('fs');

const apiKey = '******';
const imagePath = '...';
const apiUrl = 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1';

async function main() {
  const imageBase64 = fs.readFileSync(imagePath).toString('base64');

  let res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      APIKEY: apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      image_base64: imageBase64,
      mode: 'sync',
      prompt: '去除图片中的水印和遮挡文字'
    })
  });

  let data = await res.json();
  if (data.code !== 0) {
    console.error('请求失败:', data.msg_cn || data.msg);
    return;
  }

  fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
  console.log('自动去水印成功,已保存 result.jpg');

  res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      APIKEY: apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      mode: 'async_submit',
      image_base64: imageBase64,
      prompt: '去除图片中的水印'
    })
  });

  const submitData = await res.json();
  const fetchRes = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      APIKEY: apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      mode: 'async_fetch',
      image_id: submitData.image_id
    })
  });
  const fetchData = await fetchRes.json();
  console.log('异步获取结果:', fetchData);
}

main().catch(console.error);

4.5 NodeJs

const request = require("request");
const fs = require("fs");

const apiKey = '******';
const imagePath = '...';
const apiUrl = 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1';

function post(body, callback) {
  request({
    method: "POST",
    url: apiUrl,
    headers: {
      APIKEY: apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  }, callback);
}

function main() {
  const imageBase64 = fs.readFileSync(imagePath).toString('base64');

  post({
    image_base64: imageBase64,
    mode: "sync",
    prompt: "去除图片中的水印和遮挡文字"
  }, function (error, response, body) {
    if (error) {
      console.error(error);
      return;
    }
    let data = body;
    try {
      if (typeof body === 'string') data = JSON.parse(body);
    } catch (e) {}
    if (data.code !== 0) {
      console.error('请求失败:', data.msg_cn || data.msg);
      return;
    }

    fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
    console.log('自动去水印成功,已保存 result.jpg');

    post({
      image_base64: imageBase64,
      mode: "async_submit",
      prompt: "去除图片中的水印"
    }, function (error2, response2, body2) {
      if (error2) {
        console.error(error2);
        return;
      }
      let data2 = body2;
      try {
        if (typeof body2 === 'string') data2 = JSON.parse(body2);
      } catch (e) {}
      post({ mode: "async_fetch", image_id: data2.image_id }, function (error3, response3, body3) {
        if (error3) {
          console.error(error3);
          return;
        }
        let data3 = body3;
        try {
          if (typeof body3 === 'string') data3 = JSON.parse(body3);
        } catch (e) {}
        console.log('异步获取结果:', data3);
      });
    });
  });
}

main();

4.6 cURL

# 同步请求
curl -k 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"image_base64":"图片base64编码","mode":"sync","prompt":"去除图片中的水印和遮挡文字"}'

# 异步提交任务
curl -k 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"image_url":"https://example.com/demo.jpg","mode":"async_submit","prompt":"去除图片中的水印"}'

# 异步获取结果
curl -k 'http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"mode":"async_fetch","image_id":"异步提交任务返回的image_id"}'

4.7 C# 示例

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiKey = "******"; // 你的API KEY
        string filePath = "...";  // 图片路径
        string url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1";

        // 将图片编码为Base64
        string photoBase64;
        using (var imageStream = File.OpenRead(filePath))
        {
            byte[] imageBytes = new byte[imageStream.Length];
            await imageStream.ReadAsync(imageBytes, 0, (int)imageStream.Length);
            photoBase64 = Convert.ToBase64String(imageBytes);
        }

        // 构造请求数据
        var requestData = new
        {
            image_base64 = photoBase64
        };
        string jsonData = JsonSerializer.Serialize(requestData);

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("APIKEY", apiKey);

            try
            {
                // 发送POST请求
                var response = await client.PostAsync(url, new StringContent(jsonData, Encoding.UTF8, "application/json"));
                string responseString = await response.Content.ReadAsStringAsync();

                // 解析响应
                var responseObject = JsonSerializer.Deserialize<JsonElement>(responseString);

                int code = responseObject.GetProperty("code").GetInt32();
                if (code == 0)
                {
                    string resultBase64 = responseObject.GetProperty("result_base64").GetString();
                    
                    // 将Base64转换为图片并保存
                    byte[] fileBytes = Convert.FromBase64String(resultBase64);
                    File.WriteAllBytes("result.jpg", fileBytes);
                    Console.WriteLine("Image processing succeeded, saved as result.jpg");
                }
                else
                {
                    string errorMsg = responseObject.GetProperty("msg_cn").GetString();
                    Console.WriteLine($"Error: {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }
    }
}

4.8 易语言

版本 2
.支持库 spec
.支持库 dp1

.子程序 图片_API_示例
.局部变量 局_网址, 文本型
.局部变量 局_方式, 整数型
.局部变量 局_提交数据, 文本型
.局部变量 局_提交协议头, 文本型
.局部变量 局_结果, 字节集
.局部变量 局_返回, 文本型
.局部变量 图片数据, 字节集
.局部变量 base64图片, 文本型

图片数据 = 读入文件 ("你的图片路径.jpg")
base64图片 = 编码_BASE64编码 (图片数据)
局_提交数据 = "{" + #引号 + "image_base64" + #引号 + ":" + #引号 + base64图片 + #引号 + "}"
局_网址 = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
局_方式 = 1
局_提交协议头 = "APIKEY: 你的APIKEY" + #换行符 + "Content-Type: application/json"
局_结果 = 网页_访问_对象 (局_网址, 局_方式, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
返回 (局_返回)

4.9 天诺

public static string Api_Image64(Image image, string apiKey)
{
    string url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1";
    var headers = new Dictionary
    {
        {"Authorization", "APPCODE " + appcode},
        {"Content-Type", "application/json"}
    };
    string body = "{\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
    return CustomHelp.HttpPost(url, body, headers);
}

4.10 按键精灵-电脑版

Import "Encrypt.dll"
VBSBegin
Function Base64Encode(filePath)
    Set inStream = CreateObject("ADODB.Stream")
    inStream.Type = 1
    inStream.Open
    inStream.LoadFromFile filePath
    inStream.Position = 0
    Set dom = CreateObject("MSXML2.DOMDocument")
    Set elem = dom.createElement("tmp")
    elem.dataType = "bin.base64"
    elem.nodeTypedValue = inStream.Read
    Base64Encode = elem.Text
    inStream.Close
End Function

Function api_image64(apiKey, imgPath)
    url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
    jsonBody = "{""image_base64"":""" & Base64Encode(imgPath) & """}"
    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "POST", url, False
    http.setRequestHeader "APIKEY", apiKey
    http.setRequestHeader "Content-Type", "application/json"
    http.send jsonBody
    api_image64 = http.responseText
End Function
VBSEnd

apiKey = "你的APIKEY"
res = api_image64(apiKey, "你的图片路径.jpg")
TracePrint res

4.11 按键精灵-手机版

Import "yd.luae"
Import "zm.luae"

Dim imagePath = "/sdcard/Pictures/test.png"
SnapShotEx imagePath

Function api_image64(apiKey, imagePath)
    Dim url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
    Dim body = "{""image_base64"":""" & yd.Base64EncodeFile(imagePath) & """}"
    Dim headers = {null}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    Dim res = yd.HttpPost(url, body, headers)
    api_image64 = yd.JsonDecode(res)
End Function

Dim apiKey = "你的APIKEY"
Dim res = api_image64(apiKey, imagePath)
TracePrint res["code"]

4.12 触动精灵

require("tsnet")
require "TSLib"
local ts = require("ts")
local json = ts.json

function readFileBase64(path)
    local f = io.open(path,"rb")
    if not f then return nil end
    local bytes = f:read("*all")
    f:close()
    return bytes:base64_encode()
end

function api_image64(apiKey, imagePath)
    local url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
    local body = json.encode({ image_base64 = readFileBase64(imagePath) })
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local resp = httpPost(url, body, { headers = headers })
    return json.decode(resp)
end

4.13 懒人精灵

function api_image64(apiKey, imagePath)
    local url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
    local body = jsonLib.encode({ image_base64 = getFileBase64(imagePath) })
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local resp = httpPost(url, body, { headers = headers })
    return jsonLib.decode(resp)
end

4.14 EasyClick

function main()
    local request = image.requestScreenCapture(10000, 0)
    if not request then
        request = image.requestScreenCapture(10000, 0)
    end
    local apiKey = "你的APIKEY"
    local img = image.captureFullScreenEx()
    console.time("t")
    local res = api_image64(apiKey, img)
    logd(console.timeEnd("t"))
    logd(res.code)
end

function api_image64(apiKey, img)
    local url = "http(s)://api.shiliuai.com/api/auto_inpaint_advanced/v1"
    local imgBase64 = image.toBase64Format(img, "jpg", 100)
    image.recycle(img)
    local body = JSON.stringify({ image_base64 = imgBase64 })
    local params = {
        url = url,
        method = "POST",
        headers = {
            ["APIKEY"] = apiKey,
            ["Content-Type"] = "application/json"
        },
        requestBody = body
    }
    local res = http.request(params)
    return JSON.parse(res.body)
end