可立图 ClipImg 专业人像抠图 API 服务
接口概述 #
本接口基于先进的深度学习算法,提供专业级的人像抠图服务。它能够精准识别图像中的人物主体,自动将人像与背景进行像素级分割,并处理发丝、半透明衣物等边缘细节,输出高质量的透明背景图片(PNG)。
核心优势:
- 发丝级精细度:对头发丝、镂空衣物等复杂边缘有极佳的处理效果。
- 全场景适应:支持纯色、复杂背景、夜景、多人合影等多种场景。
- 多种输出格式:支持直接返回透明PNG流,或返回包含Alpha通道的ZIP包,以及JSON格式的预览/下载链接。
典型使用场景 #
- 电商设计:自动提取模特人像,快速更换背景制作商品详情页或营销海报。
- 证件照制作:分离人像后,可自由更换红/蓝/白等底色,用于制作各类证件照。
- 互动娱乐:用于制作表情包、人像贴纸、换背景特效等趣味应用。
- 图像编辑工具:为在线设计工具或修图APP提供“一键抠图”的核心能力。
- 虚拟形象/元宇宙:提取真人形象用于生成数字分身或合成虚拟场景。
- 接口地址:
https://www.clipimg.com/api/human/matting - 在线演示: 试一试
- Postman: 文档
- 请求方式:
POST - Content-Type:
multipart/form-data或application/json - 需要API Key: 是
限制说明 #
- 图片尺寸:最大支持 2000x2000px
- 文件大小:小于 10MB(超过限制会自动压缩)
请求格式 #
Headers #
X-API-Key: your_api_key_here
请求体参数 #
方式一:multipart/form-data(推荐)
| 参数 | 类型 | 必选 | 说明 |
|---|---|---|---|
| file | binary | 是 | 图片文件二进制流 |
| format | string | 否 | 返回数据格式,可选值:png (默认), zip, json |
| watermark_id | string | 否 | 水印标识符 (仅 format=json 时生效)。用于指定自定义水印,可在个人中心-API管理中上传并获取。若不设置,使用默认水印。 |
方式二:application/json
{
"file": "base64_encoded_image_data...",
"format": "png",
"watermark_id": "your_watermark_id"
}
| 参数 | 类型 | 必选 | 说明 |
|---|---|---|---|
| file | string | 是 | 图片的 Base64 编码字符串(不包含 data:image/xxx;base64, 前缀) |
| format | string | 否 | 返回数据格式,可选值:png (默认), zip, json |
| watermark_id | string | 否 | 水印标识符 (仅 format=json 时生效)。用于指定自定义水印。 |
format参数说明 #
- png: 直接返回扣除背景后的 PNG 透明图片二进制流(默认)。
- zip: 返回包含 alpha 通道图和透明 PNG 图的 ZIP 压缩包二进制流。
- json: 返回 JSON 格式数据,包含预览图(含水印)地址和下载(无水印)地址。
计费说明 #
- format=png 或 zip: 调用成功即扣除 50 点。
- format=json:
- 获取预览图(含水印)不扣点。
- 调用下载接口获取无水印结果时扣除 50 点。
响应格式 #
1. format=png (默认) #
HTTP状态码为 200,Header Content-Type: image/png,Body 为图片二进制数据。
2. format=zip #
HTTP状态码为 200,Header Content-Type: application/octet-stream,Body 为 ZIP 文件二进制数据。
3. format=json #
HTTP状态码为 200,Header Content-Type: application/json。
成功响应示例:
{
"code": 0,
"msg": "Success",
"data": {
"download_url": "https://www.clipimg.com/api/human/matting/download/unique_image_id_xxx_matte",
"preview_url": "https://www.clipimg.com/api/human/matting/preview/unique_image_id_xxx_matte_preview",
"preview_img_name": "unique_image_id_xxx_matte_preview",
"img_name": "unique_image_id_xxx_matte"
}
}
错误响应 #
{
"code": 402,
"msg": "您的API点数已用完,请及时充值",
"data": []
}
状态码说明 #
| 状态码 | 说明 |
|---|---|
| 0 | 成功 |
| 400 | 参数错误 / 文件读取失败 / 无法解析图片 |
| 402 | 您的API点数已用完,请及时充值 |
| 403 | API Key error (密钥错误) |
| 413 | Upload file size exceeds limit (文件大小超出限制) |
| 509 | 处理超时,请稍后再试 |
错误码详细说明 #
- 400 参数错误:可能原因包括
文件数据为空、无法解析图片数据、无法解码图片,请检查图片格式、缺少file参数等。 - 402 您的API点数已用完…:账户余额不足。
- 413 Upload file size exceeds limit:上传的文件超过了服务器限制(通常为10MB)。
- 509 处理超时…:图片处理耗时过长,请重试或使用更小的图片。
图片访问URL (format=json模式) #
预览图片 #
- 接口:
/human/matting/preview/{preview_img_name} - 方式:
GET - 说明: 免费,返回带水印的预览图。其中
{preview_img_name}对应响应中的preview_img_name字段。
下载图片 #
- 接口:
/human/matting/download/{img_name} - 方式:
POST - 说明: 扣费操作。需要 Header 中带上
X-API-Key。其中{img_name}对应响应中的img_name字段。
各语言调用示例 #
以下示例演示调用 /human/matting 接口,使用域名 https://www.clipimg.com/api。
curl #
# 1. 直接保存为图片 (format=png)
curl -X POST "https://www.clipimg.com/api/human/matting" \
-H "X-API-Key: YOUR_API_KEY" \
-F "file=@photo.jpg" \
-F "format=png" \
--output result.png
# 2. 获取JSON结果 (format=json)
curl -X POST "https://www.clipimg.com/api/human/matting" \
-H "X-API-Key: YOUR_API_KEY" \
-F "file=@photo.jpg" \
-F "format=json" \
-F "watermark_id=your_watermark_id"
Python (requests) #
import requests
import json
api_url = "https://www.clipimg.com/api/human/matting"
api_key = "YOUR_API_KEY"
file_path = "photo.jpg"
# 示例1: 直接获取结果图片 (format=png)
def matting_binary():
files = {"file": open(file_path, "rb")}
data = {"format": "png"}
headers = {"X-API-Key": api_key}
response = requests.post(api_url, headers=headers, files=files, data=data)
if response.status_code == 200:
with open("result.png", "wb") as f:
f.write(response.content)
print("抠图成功,已保存为 result.png")
else:
print(f"Error: {response.text}")
# 示例2: 获取预览和下载链接 (format=json)
def matting_json():
files = {"file": open(file_path, "rb")}
data = {
"format": "json",
# "watermark_id": "your_id" # 可选
}
headers = {"X-API-Key": api_key}
response = requests.post(api_url, headers=headers, files=files, data=data)
if response.status_code == 200:
result = response.json()
if result['code'] == 0:
print("预览图URL:", result['data']['preview_url'])
print("下载链接:", result['data']['download_url'])
# 注意:下载链接需要POST请求并带上API Key
else:
print("Error:", result['msg'])
else:
print(f"Http Error: {response.status_code}")
if __name__ == "__main__":
matting_binary()
# matting_json()
Node.js (axios) #
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const API_KEY = 'YOUR_API_KEY';
const FILE_PATH = 'photo.jpg';
const API_URL = 'https://www.clipimg.com/api/human/matting';
// 示例1: 直接获取结果图片 (format=png)
async function mattingBinary() {
const form = new FormData();
form.append('file', fs.createReadStream(FILE_PATH));
form.append('format', 'png');
try {
const response = await axios.post(API_URL, form, {
headers: {
'X-API-Key': API_KEY,
...form.getHeaders()
},
responseType: 'arraybuffer' // 关键:接收二进制数据
});
fs.writeFileSync('result.png', response.data);
console.log('抠图成功,已保存为 result.png');
} catch (error) {
console.error('Error:', error.response ? error.response.data.toString() : error.message);
}
}
// 示例2: 获取预览和下载链接 (format=json)
async function mattingJson() {
const form = new FormData();
form.append('file', fs.createReadStream(FILE_PATH));
form.append('format', 'json');
try {
const response = await axios.post(API_URL, form, {
headers: {
'X-API-Key': API_KEY,
...form.getHeaders()
}
});
console.log('Response:', response.data);
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
mattingBinary();
PHP (cURL) #
<?php
$apiKey = "YOUR_API_KEY";
$filePath = realpath('photo.jpg');
$apiUrl = "https://www.clipimg.com/api/human/matting";
// 示例1: 直接获取结果图片 (format=png)
function mattingBinary($apiUrl, $apiKey, $filePath) {
$ch = curl_init();
$cfile = new CURLFile($filePath);
$data = array('file' => $cfile, 'format' => 'png');
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-Key: $apiKey"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
file_put_contents("result.png", $result);
echo "抠图成功,已保存为 result.png\n";
} else {
echo "Error: " . $result . "\n";
}
}
// 示例2: 获取预览和下载链接 (format=json)
function mattingJson($apiUrl, $apiKey, $filePath) {
$ch = curl_init();
$cfile = new CURLFile($filePath);
$data = array('file' => $cfile, 'format' => 'json');
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-Key: $apiKey"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$json = json_decode($result, true);
print_r($json);
} else {
echo "Error: " . $result . "\n";
}
}
mattingBinary($apiUrl, $apiKey, $filePath);
?>
Java (OkHttp) #
import okhttp3.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MattingDemo {
private static final String API_KEY = "YOUR_API_KEY";
private static final String API_URL = "https://www.clipimg.com/api/human/matting";
public static void main(String[] args) throws IOException {
mattingBinary();
// mattingJson();
}
// 示例1: 直接获取结果图片 (format=png)
public static void mattingBinary() throws IOException {
OkHttpClient client = new OkHttpClient();
File file = new File("photo.jpg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("image/jpeg"), file))
.addFormDataPart("format", "png")
.build();
Request request = new Request.Builder()
.url(API_URL)
.addHeader("X-API-Key", API_KEY)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
FileOutputStream fos = new FileOutputStream("result.png");
fos.write(response.body().bytes());
fos.close();
System.out.println("抠图成功,已保存为 result.png");
} else {
System.out.println("Error: " + response.body().string());
}
}
}
// 示例2: 获取预览和下载链接 (format=json)
public static void mattingJson() throws IOException {
OkHttpClient client = new OkHttpClient();
File file = new File("photo.jpg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("image/jpeg"), file))
.addFormDataPart("format", "json")
.build();
Request request = new Request.Builder()
.url(API_URL)
.addHeader("X-API-Key", API_KEY)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println("Response: " + response.body().string());
} else {
System.out.println("Error: " + response.body().string());
}
}
}
}
下载无水印图片(示例) #
curl #
curl -X POST "https://www.clipimg.com/api/human/matting/download/{img_name}" \
-H "X-API-Key: YOUR_API_KEY" \
--output result_matte.png
Python (requests) #
import requests
api_key = "YOUR_API_KEY"
img_name = "{img_name}" # 替换为实际的 image_id + _matte
url = f"https://www.clipimg.com/api/human/matting/download/{img_name}"
headers = {"X-API-Key": api_key}
# 注意:下载接口需要使用 POST 方法
with requests.post(url, headers=headers, stream=True) as r:
if r.status_code == 200:
with open("result_matte.png", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print("下载成功")
else:
print(f"下载失败: {r.status_code} - {r.text}")
Node.js (axios) #
const axios = require('axios');
const fs = require('fs');
const API_KEY = 'YOUR_API_KEY';
const IMG_NAME = '{img_name}'; // 替换为实际的 image_id + _matte
const URL = `https://www.clipimg.com/api/human/matting/download/${IMG_NAME}`;
async function downloadImage() {
try {
const response = await axios.post(URL, {}, {
headers: { 'X-API-Key': API_KEY },
responseType: 'arraybuffer'
});
fs.writeFileSync('result_matte.png', response.data);
console.log('下载成功');
} catch (error) {
console.error('下载失败:', error.response ? error.response.status : error.message);
}
}
downloadImage();
PHP (cURL) #
<?php
$apiKey = 'YOUR_API_KEY';
$imgName = '{img_name}'; // 替换为实际的 image_id + _matte
$url = "https://www.clipimg.com/api/human/matting/download/$imgName";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["X-API-Key: $apiKey"],
CURLOPT_RETURNTRANSFER => true,
]);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
file_put_contents('result_matte.png', $data);
echo "下载成功\n";
} else {
echo "下载失败: $httpCode\n";
}
?>
Java (OkHttp) #
import java.nio.file.*;
import okhttp3.*;
public class DownloadMatteDemo {
public static void main(String[] args) throws Exception {
String imgName = "{img_name}"; // 替换为实际的 image_id + _matte
String url = "https://www.clipimg.com/api/human/matting/download/" + imgName;
String apiKey = "YOUR_API_KEY";
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(new byte[0], null);
Request req = new Request.Builder()
.url(url)
.addHeader("X-API-Key", apiKey)
.post(body)
.build();
try (Response resp = client.newCall(req).execute()) {
if (resp.isSuccessful()) {
Files.write(Paths.get("result_matte.png"), resp.body().bytes());
System.out.println("下载成功");
} else {
System.out.println("下载失败: " + resp.code());
}
}
}
}
