AI智能擦除
POST
http://***/inpaint_image_sync消耗: 1 积分 / 5次此接口用于同步处理AI智能擦除任务,接收原图和蒙版图片(Base64 格式),直接返回擦除后的图片数据流。
请求参数
| 名称 | 类型 | 必填 | 描述 |
|---|---|---|---|
| AccountId | string | 是 | 账号ID。 |
| image | string | 是 | 原图 Base64 编码。 |
| mask | string | 是 | 蒙版图片 Base64 编码,用于指定修复区域。 |
| Signature | string | 是 | 请求签名,用于验证请求合法性,参见"验签方式"。 |
返回示例
(成功时直接返回二进制图片流,无 JSON)注意:每次调用会记录使用次数,当累计达到 5 次时扣除 1 个积分。如果积分不足,请求将返回 403 InsufficientPoints 错误。
失败时的 JSON 示例:
{
"Code": 400,
"Message": "缺少必要的参数: 'image', 'mask', 'AccountId'",
"ErrorCode": "MissingParameters"
}Python 调用示例
# -*- coding: utf-8 -*-
import base64
import hashlib
import hmac
import json
import time
import mimetypes
import requests
API_ENDPOINT = "http://***/inpaint_image_sync"
ACCOUNT_ID = "pic_YOUR_ID"
SECRET_KEY = "YOUR_SECRET_KEY"
OUTPUT_FILE = "inpaint-result.png"
def generate_signature(params, secret_key):
sorted_params = sorted(params.items())
param_string = "&".join(
f"{key}={value}"
for key, value in sorted_params
if value is not None and value != "" and key != "Signature"
)
sign_string = f"{param_string}&SecretKey={secret_key}"
signature = hmac.new(
secret_key.encode("utf-8"),
sign_string.encode("utf-8"),
hashlib.sha256
).digest()
return base64.b64encode(signature).decode("utf-8")
def read_image_as_base64(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type:
mime_type = "image/jpeg"
with open(file_path, "rb") as image_file:
image_base64 = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{image_base64}"
def call_api():
params = {
"AccountId": ACCOUNT_ID,
"image": read_image_as_base64("image.png"),
"mask": read_image_as_base64("mask.png"),
}
params["Signature"] = generate_signature(params, SECRET_KEY)
response = requests.post(API_ENDPOINT, json=params, timeout=60)
content_type = response.headers.get("Content-Type", "")
if response.ok and "application/json" not in content_type:
with open(OUTPUT_FILE, "wb") as output:
output.write(response.content)
print(f"处理完成,结果已保存到 {OUTPUT_FILE}")
return
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except ValueError:
print(response.text)
if __name__ == "__main__":
call_api()Java 调用示例
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class PicTechInpaintDemo {
private static final String API_URL = "http://***/inpaint_image_sync";
private static final String ACCOUNT_ID = "pic_YOUR_ID";
private static final String SECRET_KEY = "YOUR_SECRET_KEY";
private static final String OUTPUT_FILE = "inpaint-result.png";
public static void main(String[] args) throws Exception {
Map<String, Object> params = new TreeMap<>();
params.put("AccountId", ACCOUNT_ID);
params.put("image", readImageAsBase64("image.png"));
params.put("mask", readImageAsBase64("mask.png"));
params.put("Signature", generateSignature(params, SECRET_KEY));
String jsonBody = buildJson(params);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
String contentType = response.headers().firstValue("Content-Type").orElse("");
if (response.statusCode() >= 200 && response.statusCode() < 300 && !contentType.contains("application/json")) {
Files.write(Path.of(OUTPUT_FILE), response.body());
System.out.println("处理完成,结果已保存到 " + OUTPUT_FILE);
} else {
System.out.println(new String(response.body(), StandardCharsets.UTF_8));
}
}
private static String generateSignature(Map<String, Object> params, String secretKey) throws Exception {
String paramString = params.entrySet().stream()
.filter(entry -> entry.getValue() != null && !entry.getValue().toString().isEmpty())
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
String signString = paramString + "&SecretKey=" + secretKey;
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return Base64.getEncoder().encodeToString(
hmacSha256.doFinal(signString.getBytes(StandardCharsets.UTF_8))
);
}
private static String buildJson(Map<String, Object> params) {
return "{" + params.entrySet().stream()
.map(entry -> "\"" + entry.getKey() + "\":" + toJsonValue(entry.getValue()))
.collect(Collectors.joining(",")) + "}";
}
private static String toJsonValue(Object value) {
if (value instanceof Number || value instanceof Boolean) {
return value.toString();
}
return "\"" + escapeJson(value.toString()) + "\"";
}
private static String escapeJson(String value) {
return value
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
}
private static String readImageAsBase64(String path) throws IOException {
byte[] bytes = Files.readAllBytes(Path.of(path));
String lowerPath = path.toLowerCase(Locale.ROOT);
String mimeType = "image/jpeg";
if (lowerPath.endsWith(".png")) {
mimeType = "image/png";
} else if (lowerPath.endsWith(".webp")) {
mimeType = "image/webp";
} else if (lowerPath.endsWith(".gif")) {
mimeType = "image/gif";
}
return "data:" + mimeType + ";base64," + Base64.getEncoder().encodeToString(bytes);
}
}
