1. 接口说明
结婚证件照制作接口 API:基于自研深度学习算法与图像处理技术,实现从普通生活照一键生成结婚证件照。接口内部集成人脸检测、人像裁剪、背景抠除与颜色替换、美颜处理以及排版打印能力,开发者只需上传原始照片及少量参数,即可获得符合规格要求的结婚证件照成品。
1.1 主要功能
- 全规格支持:
- 可自定义证件照宽高(像素或毫米)、DPI 分辨率、目标文件大小(KB),满足不同结婚证件照规格需求。
- 智能抠图与换底:
- 自动识别人像并完成精细抠图,可将背景替换为指定纯色或渐变色,常用背景包括红色、蓝色、白色等。
- 美颜与质量增强:
- 支持自动与自定义参数的磨皮、瘦脸、调光、锐化等操作,提升结婚证件照观感与清晰度。
- 预览与加水印:
- 可通过参数开启预览模式,加水印展示生成效果,不扣积分,方便前端交互体验与效果确认。
- 排版打印:
- 支持返回 5 寸或 6 寸相纸排版图,便于线下冲印结婚证件照。
1.2 接入场景
适用于结婚登记预约平台、小程序/APP 中的结婚证件照拍摄与制作、婚庆服务机构的证件照增值服务,以及线下自助终端的结婚证件照快速生成等场景。
2. 请求信息
2.1 请求地址(URL)
POST https://api.shiliuai.com/api/id_photo/v1/couple
2.2 请求方式
POST
2.3 请求头(header)
| 参数 | 类型 | 说明 |
|---|---|---|
| Content-Type | string | application/json |
| APIKEY | string | 您的 API KEY |
2.4 请求体(body)
| 参数 | 是否必填 | 类型 | 说明 |
|---|---|---|---|
| 图片 | |||
| base64 | 必须填写其中之一 | string | base64 编码的图片文件(小于 20M) |
| url | string | 图片文件url(小于20M) | |
| id | string | 图片 id,对于已经请求过的图片,如果需要改变水印、尺寸、颜色等参数,可直接使用 id 而无需再次上传 base64和url | |
| 尺寸 | |||
| dpi | 否 | int | 生成证件照的 DPI,默认为 300,最大值 1000 |
| pxWidth | 否 | int | 生成证件照宽度(像素),可与 pxHeight 搭配,或与毫米尺寸互斥,默认 (295, 413),小于 1800 像素 |
| pxHeight | 否 | int | 生成证件照高度(像素),小于 1800 像素 |
| mmWidth | 否 | int | 生成证件照宽度(毫米),小于 180 毫米 |
| mmHeight | 否 | int | 生成证件照高度(毫米),小于 180 毫米 |
| 背景色 | |||
| changeBg | 否 | int | 0 或 1,是否抠图换背景,默认为 1 |
| bgColor | 否 | string | 背景色 16 进制表示,常用颜色:白色 "FFFFFF",红色 "FF0000",蓝色 "438EDB",默认为白色 |
| 美颜 | |||
| autoBright | 否 | int | 0 或 1,是否自动调光,默认为 0 |
| brightFactor | 否 | float | [0, 1],调光系数,默认为 0.5 |
| autoSmooth | 否 | int | 0 或 1,是否自动磨皮,默认为 0 |
| smoothFactor | 否 | float | [0, 1],磨皮系数,默认为 0.5 |
| autoThinFace | 否 | int | 0 或 1,是否自动瘦脸,默认为 0 |
| thinFaceFactor | 否 | float | [0, 1],瘦脸系数,默认为 0.5 |
| autoSharp | 否 | int | 0 或 1,是否自动锐化,默认为 0 |
| sharpFactor | 否 | float | [0, 1],锐化系数,默认为 0.5 |
| 预览 | |||
| preview | 否 | int | 0 或 1,是否仅预览。预览图有水印且不扣积分,默认为 0 |
| watermarkID | 否 | string | 定制化水印 id,默认使用系统水印 |
| 文件大小 | |||
| quality | 否 | int | 生成证件照质量,[1, 100],数值越大文件越大,默认为 92 |
| minFileSize | 否 | int | 最小文件大小(KB),例如 10240 表示 10KB,仅在 quality 为空时生效 |
| maxFileSize | 否 | int | 最大文件大小(KB),仅在 quality 为空时生效 |
| 排版 | |||
| layout | 否 | int | 0 或 1,是否返回排版图,默认为 0 |
| layoutVertical | 否 | int | 0 或 1,返回横版或竖版排版,默认为横版 |
| layoutSize | 否 | string | "5inch" 或 "6inch",排版尺寸为五寸或六寸,默认为 "5inch" |
3. 返回信息
3.1 返回类型
JSON
3.2 返回字段
| 参数 | 说明 |
|---|---|
| code | 错误码 |
| msg | 错误信息(英文) |
| msg_cn | 错误信息(中文) |
| id | 图片 id,当 code==0 时返回 |
| result_base64 | 结婚证件照成品的 base64 编码,当 code==0 时返回 |
| layout_base64 | 排版图的 base64 编码,当 code==0 且请求参数 layout==1 时返回 |
3.3 返回示例
{
"code": 0,
"msg": "OK",
"msg_cn": "成功",
"id": "xxxxxx",
"result_base64": "结婚证件照 base64 数据",
"layout_base64": "结婚证件照排版 base64 数据(当请求参数 layout==1 时返回)"
}
3.4 错误码说明
| 错误码 | 说明 |
|---|---|
| 0 | 成功 |
| 1 | 图片错误 |
| 2 | 抠图错误 |
| 3 | 服务器繁忙 |
| 4 | 参数错误,具体错误请参考 msg 或 msg_cn |
| 6 | 未知错误 |
| 7 | 图片 id 无效,可能已过期 |
| 8 | 图片人脸数不是 2(结婚证件照通常为两人合照) |
| 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
file_path = '...' # 图片路径
with open(file_path, 'rb') as fp:
photo_base64 = base64.b64encode(fp.read()).decode('utf8')
url = 'https://api.shiliuai.com/api/id_photo/v1/couple'
headers = {'APIKEY': api_key, "Content-Type": "application/json"}
data = {
"base64": photo_base64,
}
response = requests.post(url=url, headers=headers, json=data)
response = json.loads(response.content)
"""
成功:{'code': 0, 'msg': 'OK', 'msg_cn': '成功', 'id': image_id, 'result_base64': result_base64}
or
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息}
"""
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)
4.2 PHP
<?php
$url = "https://api.shiliuai.com/api/id_photo/v1/couple";
$method = "POST";
$apikey = "******";
$header = array();
array_push($header, "APIKEY:" . $apikey);
array_push($header, "Content-Type:application/json");
$file_path = "...";
$handle = fopen($file_path, "r");
$photo = fread($handle, filesize($file_path));
fclose($handle);
$photo_base64 = base64_encode($photo);
$data = array(
"base64"=> $photo_base64,
);
$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 CoupleIDPhotoAPIExample {
public static void main(String[] args) {
String apiKey = "******"; // 你的API KEY
String filePath = "path/to/your/image.jpg"; // 图片路径
try {
// 读取图片并编码为 Base64
byte[] fileBytes = Files.readAllBytes(new File(filePath).toPath());
String photoBase64 = Base64.getEncoder().encodeToString(fileBytes);
// API 请求的 URL
String apiUrl = "https://api.shiliuai.com/api/id_photo/v1/couple";
// 请求参数
JSONObject requestData = new JSONObject();
requestData.put("base64", photoBase64);
// 发送 POST 请求
JSONObject response = sendPostRequest(apiUrl, apiKey, requestData);
// 检查响应是否成功
if (response.getInt("code") == 0) {
String resultBase64 = response.getString("result_base64");
// 解码并保存图片
byte[] resultBytes = Base64.getDecoder().decode(resultBase64);
try (FileOutputStream fos = new FileOutputStream("result_couple.jpg")) {
fos.write(resultBytes);
}
System.out.println("结婚证件照生成成功,文件已保存为 result_couple.jpg");
} else {
System.out.println("请求失败: " + response.getString("msg_cn"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 发送 POST 请求
private static JSONObject sendPostRequest(String urlStr, String apiKey, JSONObject jsonData) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("APIKEY", apiKey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// 写入请求数据
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
// 读取响应
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
return new JSONObject(response.toString());
}
}
4.4 JavaScript
const fs = require('fs');
const fetch = require('node-fetch'); // 需安装:npm install node-fetch
const apiKey = '******'; // 你的API KEY
const filePath = 'path/to/your/image.jpg'; // 图片路径
(async () => {
try {
// 读取图片并编码为 Base64
const fileBuffer = fs.readFileSync(filePath);
const photoBase64 = fileBuffer.toString('base64');
// API 请求的 URL
const apiUrl = 'https://api.shiliuai.com/api/id_photo/v1/couple';
// 请求参数
const requestData = {
base64: photoBase64
};
// 发送 POST 请求
let response = await fetch(apiUrl, {
method: 'POST',
headers: {
'APIKEY': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
});
const responseData = await response.json();
// 检查响应是否成功
if (responseData.code === 0) {
const resultBase64 = responseData.result_base64;
const resultBuffer = Buffer.from(resultBase64, 'base64');
fs.writeFileSync('result_couple.jpg', resultBuffer);
console.log('结婚证件照生成成功,文件已保存为 result_couple.jpg');
} else {
console.error('请求失败:', responseData.msg_cn);
}
} catch (error) {
console.error('发生错误:', error);
}
})();
4.5 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()
{
var apiKey = "******";
var filePath = "path/to/your/image.jpg";
var url = "https://api.shiliuai.com/api/id_photo/v1/couple";
var photoBase64 = Convert.ToBase64String(File.ReadAllBytes(filePath));
var request = new { base64 = photoBase64 };
var jsonData = JsonSerializer.Serialize(request);
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("APIKEY", apiKey);
var res = await client.PostAsync(url, new StringContent(jsonData, Encoding.UTF8, "application/json"));
var json = await res.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var code = root.GetProperty("code").GetInt32();
if (code == 0)
{
var resultBase64 = root.GetProperty("result_base64").GetString();
File.WriteAllBytes("result_couple.jpg", Convert.FromBase64String(resultBase64));
Console.WriteLine("结婚证件照生成成功,文件已保存为 result_couple.jpg");
}
else
{
var msg = root.TryGetProperty("msg_cn", out var msgCn) ? msgCn.GetString() : root.GetProperty("msg").GetString();
Console.WriteLine("请求失败: " + msg);
}
}
}
4.6 易语言
版本 2
.支持库 spec
.支持库 dp1
.子程序 结婚证件照_API_示例
.局部变量 局_网址, 文本型
.局部变量 局_方式, 整数型
.局部变量 局_提交数据, 文本型
.局部变量 局_提交协议头, 文本型
.局部变量 局_结果, 字节集
.局部变量 局_返回, 文本型
.局部变量 图片数据, 字节集
.局部变量 base64图片, 文本型
图片数据 = 读入文件 ("你的图片路径.jpg")
base64图片 = 编码_BASE64编码 (图片数据)
局_提交数据 = "{" + #引号 + "base64" + #引号 + ":" + #引号 + base64图片 + #引号 + "}"
局_网址 = "https://api.shiliuai.com/api/id_photo/v1/couple"
局_方式 = 1
局_提交协议头 = "APIKEY: 你的APIKEY" + #换行符 + "Content-Type: application/json"
局_结果 = 网页_访问_对象 (局_网址, 局_方式, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
返回 (局_返回)
4.7 天诺
public static string Api_Couple(Image image, string apiKey)
{
string url = "https://api.shiliuai.com/api/id_photo/v1/couple";
var headers = new Dictionary
{
{"Authorization", "APPCODE " + appcode},
{"Content-Type", "application/json"}
};
string body = "{\"base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
return CustomHelp.HttpPost(url, body, headers);
}
4.8 按键精灵-电脑版
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_couple(apiKey, imgPath)
url = "https://api.shiliuai.com/api/id_photo/v1/couple"
jsonBody = "{""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_couple = http.responseText
End Function
VBSEnd
apiKey = "你的APIKEY"
res = api_couple(apiKey, "你的图片路径.jpg")
TracePrint res
4.9 按键精灵-手机版
Import "yd.luae"
Import "zm.luae"
Dim imagePath = "/sdcard/Pictures/test.png"
SnapShotEx imagePath
Function api_couple(apiKey, imagePath)
Dim url = "https://api.shiliuai.com/api/id_photo/v1/couple"
Dim body = "{""base64"":""" & yd.Base64EncodeFile(imagePath) & """}"
Dim headers = {null}
headers["APIKEY"] = apiKey
headers["Content-Type"] = "application/json"
Dim res = yd.HttpPost(url, body, headers)
api_couple = yd.JsonDecode(res)
End Function
Dim apiKey = "你的APIKEY"
Dim res = api_couple(apiKey, imagePath)
TracePrint res["code"]
4.10 触动精灵
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_couple(apiKey, imagePath)
local url = "https://api.shiliuai.com/api/id_photo/v1/couple"
local body = json.encode({ 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.11 懒人精灵
function api_couple(apiKey, imagePath)
local url = "https://api.shiliuai.com/api/id_photo/v1/couple"
local body = jsonLib.encode({ 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.12 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_couple(apiKey, img)
logd(console.timeEnd("t"))
logd(res.code)
end
function api_couple(apiKey, img)
local url = "https://api.shiliuai.com/api/id_photo/v1/couple"
local imgBase64 = image.toBase64Format(img, "jpg", 100)
image.recycle(img)
local body = JSON.stringify({ 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