1.接口说明

证件照制作/检测 API:采用自研深度学习算法与图像处理技术,集成人脸检测、人像裁剪、背景抠除与背景色替换、美颜、换衣服、排版,以及普通/高级合规检测能力,实现普通生活照到标准证件照的自动化处理。

1.1主要功能

全规格支持:
支持自定义像素/毫米尺寸、DPI、背景色(纯色/渐变/透明)与输出大小控制(质量/文件大小)。
智能裁剪与人像调整:
按头顶、下巴、眼睛位置等约束裁剪与调整,满足各类证照规范。
抠图换底:
可抠图并替换背景色,也可返回透明底证件照。
美颜:
支持磨皮、瘦脸、调光、锐化等能力,提升成片观感。
换装:
支持男/女/儿童多套正装换装模板。
排版与预览:
支持 5 寸/6 寸排版输出与带水印预览(预览不扣积分)。
合规检测:
支持普通合规(尺寸/位置/角度等)与高级合规(遮挡/姿势/曝光/模糊/妆容等)检测结果返回。

1.2接入场景

支持小程序、APP、采集设备等接入,适用于护照/签证照片生成、身份证/社保卡/学生证/工作证等标准化证照制作与检测。

2.请求信息

2.1请求地址(URL)

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

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
规格
specID 否 int 规格ID,规格对应证件照的尺寸,背景色,人脸尺寸,文件大小,高级合规检测标准,请参考 规格列表
specVersion 否 int 规格版本
尺寸
dpi 否 int 生成证件照的dpi,默认为300,最小值10,最大值1000
pxWidth 否 int 生成证件照的宽度(像素),可传入 (pxWidth, pxHeight) 或者 (mmWidth, mmHeight) 中的一对值,默认为 (295, 413),小于1800像素
pxHeight 否 int 生成证件照的高度(像素),小于1800像素
mmWidth 否 int 生成证件照的宽度(毫米),小于180毫米
mmHeight 否 int 生成证件照的高度(毫米),小于180毫米
背景
changeBg 否 int 0或1,是否抠图换背景,默认为1
transparentBg 否 int 0或1,是否返回透明底证件照,默认为0
bgColor 否 string 背景色的16进制表示,常用颜色有:白色:"FFFFFF",红色:"FF0000",蓝色:"438EDB",默认为白色
bgColor2 否 string 渐变色的16进制表示,当提供bgColor2时,背景色会从顶部的bgColor渐变到底部的bgColor2,默认为空
人脸尺寸
faceWidth 否 int 人脸宽度(像素)
minFaceWidth 否 int 最小人脸宽度(像素)
maxFaceWidth 否 int 最大人脸宽度(像素)
faceHeight 否 int 人脸长度(像素)
minFaceHeight 否 int 最小人脸长度(像素)
maxFaceHeight 否 int 最大人脸长度(像素)
headTop 否 int 头顶与上边距离(像素)
minHeadTop 否 int 头顶与上边最小距离(像素)
maxHeadTop 否 int 头顶与上边最大距离(像素)
chinTop 否 int 头顶与上边距离(像素)
minChinTop 否 int 头顶与上边最小距离(像素)
maxChinTop 否 int 头顶与上边最大距离(像素)
eyesTop 否 int 眼睛与上边距离(像素)
minEyesTop 否 int 眼睛与上边最小距离(像素)
maxEyesTop 否 int 眼睛与上边最大距离(像素)
美颜
autoBright 否 int 0或1,是否自动调光,默认为0/td>
brightFactor 否 float [0, 1],调光系数,默认为0.5
autoSmooth 否 int 0或1,是否自动磨皮,默认为0/td>
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
换装
clothesID 否 string 换正装,"man_1", ... , "man_20", "woman_1", ..., "woman_20", "child_1", ..., "child_10", 默认为空
预览
preview 否 int 0或1,是否预览,预览有水印,不扣积分,默认为0
watermarkID 否 string 定制化水印id,默认用系统水印。备选watermarkID=s1(下载后无水印),watermarkID=s2(watermark)
文件大小
quality 否 int 生成证件照的质量,[1, 100],越大生成的证件照文件越大,默认为92
minFileSize 否 int 生成证件照的最小文件大小,[0, inf],比如10240表示最小文件大小为10KB,只有当quality为空时起作用,默认为空
maxFileSize 否 int 生成证件照的最大文件大小,[0, inf],只有当quality为空时起作用,默认为空
标签
addLabel 否 int 0或1,是否在证件照底部加标签,默认为0
labelText 否 string 证件照底部标签内容,默认为空
labelHeight 否 int 证件照底部标签高度(像素),默认为30
排版
layout 否 int 0或1,是否返回排版,默认为0
layoutVertical 否 int 0或1:横版或竖版排版,默认横版
layoutParallel 否 int 0或1,[1]照片是否与排版平行,默认为True
layoutSpacing 否 int 排版照片间距,单位:像素, [None]
layoutMargin 否 int int, 排版照片边距,单位:像素, [None]
layoutSize 否 string "5inch"或"6inch",排版尺寸五寸或六寸,默认为"5inch"
layoutBgColor 否 string 排版背景色的16进制表示,比如:白色:"FFFFFF",默认为灰色
layoutLineColor 否 string 排版线条颜色的16进制表示,比如:灰色:"323232", 默认为灰色
layoutQRCodeData 否 string 排版附加二维码数据,默认为空
layoutQRCodeSize 否 int 排版附加二维码尺寸像素,默认为290
layoutLabelText 否 string 排版附加文字,换行用\n表示,默认为空
合规检测
qualify 否 int 0或1,是否返回普通合规信息,默认为0
advancedQualify 否 int 0或1,是否返回高级合规信息,默认为0

3.返回信息

3.1返回类型

JSON

3.2返回字段

参数 返回类型 说明
code int 错误码
msg string 错误信息(英文)
msg_cn string 错误信息(中文)
id string 图片id,用于同一张图片的多次请求,id的有效时间为6小时,(当code==0时会有该返回值)
result_base64 string 证件照的base64编码,(当code==0时会有该返回值)
layout_base64 string 排版的base64编码,(当code==0且请求参数layout==1时会有该返回值)
info string 普通合规信息,(当code==0且请求参数qualify==1时会有该返回值)
advanced_info string 高级合规信息,(当code==0且请求参数advancedQualify==1时会有该返回值)
request_id string 请求ID,请求的唯一码

3.3返回示例

{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "id": "xxxxxx",
  "result_base64": "/9j/4AAQSkZJRgABAQAAAQABAAD...(省略)",
  "layout_base64": "/9j/4AAQSkZJRgABAQAAAQABAAD...(可选,layout==1 时返回)",
  "info": {
    "qualified": true,
    "msg": "OK",
    "msg_cn": "合规",
    "width": 295,
    "height": 413
  },
  "advanced_info": {
    "qualified": true,
    "msg": "OK",
    "msg_cn": "高级合规"
  },
  "request_id": "req_xxxxxxxx"
}

3.4错误码

错误码 说明
0 成功
1 图片错误
2 抠图错误
3 服务器繁忙
4 参数错误(具体错误看 msg 或 msg_cn)
5 换装时没检测到人脸
6 未知错误
7 图片 id 无效(可能已过期)
101 API-KEY 不正确
102 未知用户
103 积分已用完
104 扣除积分失败

3.5 普通合规信息

分类 参数 类型 说明
综合
qualified bool 是否合规(默认由face_width, face_height, head_top, eyes_top, eyes_angle决定);(specID存在由thresholds里的阈值决定)
thresholds dict specID存在时返回:用来判断qualified的项目的阈值,有min/max_face_width, min/max_face_height等组成
msg string 合规消息(英文)
msg_cn string 合规消息(中文)
尺寸
width int 证件照宽度,单位为像素
height int 证件照高度,单位为像素
人脸
has_face bool 是否检测到人脸
face_count int 原图人脸数
rotation int 图片旋转角度(0度,90度,180度,或者270度)
判断
face_width_qualified bool 人脸宽度是否合规
face_height_qualified bool 人脸长度是否合规
face_left_qualified bool 左侧脸颊到左侧边框距离是否合规
face_right_qualified bool 右侧脸颊到右侧边框距离是否合规
head_top_qualified bool 头顶至上边距离是否合规
chin_top_qualified bool 下巴至上边距离是否合规
eyes_top_qualified bool 眼睛至上边距离是否合规
eyes_angle_qualified bool 双眼连线角度是否合规
距离与角度
face_width int 生成证件照中人脸宽度,单位为像素
face_left int 生成证件照中左侧脸颊到左侧边框距离,单位为像素
face_right int 生成证件照中右侧脸颊到右侧边框距离,单位为像素
face_height int 人脸长度,单位为像素
head_top int 头顶至上边距离,单位为像素
chin_top int 下巴至上边距离,单位为像素
eyes_top int 眼睛至上边距离,单位为像素
eyes_angle float [-pi/2, pi/2],双眼连线角度
pupil_distance int 瞳距,单位为像素
eyes_center_from_left int 双眼中心与左边距离,单位为像素
eyes_center_from_bottom int 双眼中心与下边距离,单位为像素

3.6 高级合规信息

分类 参数 类型 说明
综合
qualified bool 是否合规。(默认)如果无人脸,戴帽子,墨镜,耳机,手机,口罩,模糊,过曝或欠曝,眉毛遮挡,嘴巴张开,则不合规。 注意:其他项目不计入判断。(specID存在)由thresholds里的阈值决定
thresholds dict specID存在时返回:用来判断qualified的项目的阈值,由specID决定
msg string 合规消息(英文)
msg_cn string 合规消息(中文)
人脸
has_face bool 是否检测到人脸
face_count int 原图人脸个数
姿势
yaw float [-90, 90],人脸偏航角,决定pose_abnormal
pitch float [-90, 90],人脸俯仰角,参与 pose_abnormal 判断
roll float [-90, 90],人脸翻滚角,参与 pose_abnormal 判断
pose_abnormal bool 人脸角度异常,如果abs(yaw)>10,或者abs(pitch)>15,或者abs(roll)>10,那么为True
质量
face_overexposed_score float [0, 1],脸部过曝程度,决定face_overexposed,默认阈值为0.5
face_overexposed bool 是否脸部过曝
face_underexposed_score float [0, 1],脸部欠曝程度,决定face_underexposed,默认阈值为0.5
face_underexposed bool 是否脸部欠曝
face_exposure_uneven_score float [0, 1],阴阳脸程度,决定face_exposure_uneven,默认阈值为0.2
face_exposure_uneven bool 是否阴阳脸
face_blur_score float [0, 1],脸部模糊程度,决定face_blur,默认阈值为0.6
face_blur bool 是否脸部模糊
face_dark_score float [0, 1],脸部过暗程度,决定face_blur,默认阈值为0.5
face_dark bool 是否脸部过暗
face_color_abnormal_score float [0, 1],脸部肤色不正常程度,决定face_blur,默认阈值为0.5
face_color_abnormal bool 是否肤色不正常
image_gray_score float [0, 1], 黑白照片程度,默认阈值为0.5
image_gray bool 是否黑白照片
face_glare_score float [0, 1],脸部反光程度,默认阈值 0.5
face_glare bool 是否脸部反光
遮挡
left_eye_occlusion_score float [0, 1],左眼遮挡程度,决定left_eye_occlusion,默认阈值为0.2
left_eye_occlusion bool 是否左眼遮挡
right_eye_occlusion_score float [0, 1],右眼遮挡程度,决定right_eye_occlusion,默认阈值为0.2
right_eye_occlusion bool 是否右眼遮挡
eye_occlusion bool 是否眼睛遮挡
mouth_occlusion_score float [0, 1],嘴巴遮挡程度,决定mouth_occlusion,默认阈值为0.2
mouth_occlusion bool 是否嘴巴遮挡
nose_occlusion_score float [0, 1],鼻子遮挡程度,决定nose_occlusion,默认阈值为0.2
nose_occlusion bool 是否鼻子遮挡
left_cheek_occlusion_score float [0, 1],左脸遮挡程度,决定left_cheek_occlusion,默认阈值为0.3
left_cheek_occlusion bool 是否左脸遮挡
right_cheek_occlusion_score float [0, 1],右脸遮挡程度,决定right_cheek_occlusion,默认阈值为0.3
right_cheek_occlusion bool 是否右脸遮挡
cheek_occlusion bool 是否脸颊遮挡,当左脸或右脸遮挡时,该项为True
eyebrow_occlusion_score float [0, 1],眉毛遮挡程度,决定eyebrow_occlusion,默认阈值为0.3
eyebrow_occlusion bool 是否眉毛遮挡
ear_occlusion_score float [0, 1],耳朵遮挡程度,决定ear_occlusion,默认阈值为0.8
ear_occlusion bool 是否耳朵遮挡
头发
hair_incomplete_score float [0, 1],头发不完整程度,决定hair_incomplete,默认阈值为0.1
hair_incomplete bool 是否头发不完整
hair_color_r float [0, 255],头发颜色红色分量
hair_color_g float [0, 255],头发颜色绿色分量
hair_color_b float [0, 255],头发颜色蓝色分量
hair_dyed_score float [0, 1],染发程度,默认阈值 0.5
hair_dyed bool 是否染发
眼睛
eye_close_score float [0, 1],闭眼程度,默认阈值 0.5
eye_close bool 是否闭眼
gaze_horizontal_score float [0, 1],视线水平偏移程度,默认阈值 0.15
gaze_horizontal bool 是否视线水平偏移
gaze_vertical_score float [0, 1],视线竖直偏移程度,默认阈值 0.1
gaze_vertical bool 是否视线竖直偏移
gaze_abnormal bool 视线是否未平视前方(水平或竖直偏移为真时为 True)
red_eye_score float [0, 1],红眼程度,默认阈值 0.5
red_eye bool 是否红眼
colored_contacts_score float [0, 1],有色隐形眼镜得分,默认阈值 0.5
colored_contacts bool 是否佩戴有色隐形眼镜
耳朵
ears_asymmetric_score float [0, 1],双耳不对称程度,默认阈值 0.5
ears_asymmetric bool 是否双耳不对称
嘴巴
mouth_open_score float [0, 1],嘴巴张开程度,默认阈值 0.1
mouth_open bool 是否嘴巴张开
饰品
hat int 0 或 1,是否戴帽子
glasses int 0 或 1,是否戴眼镜
sunglasses int 0 或 1,是否戴墨镜
headphone int 0 或 1,是否戴头戴式耳机
earphone int 0 或 1,是否戴耳塞
cellphone int 0 或 1,是否使用手机
earring int 0 或 1,是否戴耳饰
mask int 0 或 1,是否戴口罩
necklace int 0 或 1,是否戴项链
glasses_glare_score float [0, 1],眼镜反光程度,默认阈值 0.5
glasses_glare bool 是否眼镜反光
heavy_makeup_score float [0, 1],浓妆程度,默认阈值 0.5
heavy_makeup bool 是否浓妆
肩膀
shoulder_incomplete_score float [0, 1],肩膀不完整程度,默认阈值 0.5
shoulder_incomplete bool 是否肩膀不完整
shoulder_imbalance_score float [0, 1],肩膀不平衡程度,默认阈值 0.5
shoulder_imbalance bool 是否肩膀不平衡
衣服
clothes_color_r float [0, 255],衣服颜色红色分量
clothes_color_g float [0, 255],衣服颜色绿色分量
clothes_color_b float [0, 255],衣服颜色蓝色分量
clothes_color_light_score float [0, 1],衣服浅色程度,默认阈值 0.75
clothes_color_light bool 是否浅色衣服
clothes_bg_similar_score float [0, 1],衣服与背景颜色相近程度,默认阈值 0.8
clothes_bg_similar bool 是否衣服背景颜色相近
shirtless_score float [0, 1],光膀程度,默认阈值 0.5
shirtless bool 是否光膀
sleeveless_score float [0, 1],背心或吊带分数,默认阈值 0.5
sleeveless bool 是否穿背心或吊带
big_clothes_score float [0, 1],臃肿外套分数,默认阈值 0.5
big_clothes bool 是否穿臃肿外套
背景
bg_color_r float [0, 255],背景颜色红色分量
bg_color_g float [0, 255],背景颜色绿色分量
bg_color_b float [0, 255],背景颜色蓝色分量
bg_color_wrong_score float [0, 1],背景颜色错误程度,默认阈值 0.5
bg_color_wrong bool 是否背景颜色错误
图片
image_gray_score float [0, 1],黑白照片程度,默认阈值 0.5
image_gray bool 是否黑白照片

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 = 'http(s)://api.shiliuai.com/api/id_photo/v1'
headers = {'APIKEY': api_key, "Content-type": "application/json"}
data = {
    "base64": photo_base64,
    "bgColor": "FFFFFF",
    "dpi": 300,
    "mmHeight": 35,
    "mmWidth": 25
}

response = requests.post(url=url, headers=headers, json=data)
response = json.loads(response.content)
"""
成功:{'code': 0, 'msg': 'OK', 'msg_cn': '成功', 'id': id, 'result_base64': result_base64}
or
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息}
"""
result_base64 = response.get('result_base64', '')
img_id = response.get('id', '')
file_bytes = base64.b64decode(result_base64) if result_base64 else b''
if file_bytes:
    with open('result.jpg', 'wb') as f:
        f.write(file_bytes)

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

# 同一张图片,参数改变,再次请求(复用 id)
data2 = {
    "id": img_id,
    "bgColor": "FF0000",
    "dpi": 300,
    "pxHeight": 640,
    "pxWidth": 480
}
response2 = requests.post(url=url, headers=headers, json=data2)
response2 = json.loads(response2.content)

4.2 PHP

<?php
$url = "http(s)://api.shiliuai.com/api/id_photo/v1";
$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,
  "bgColor"=>"FFFFFF",
  "dpi"=>300,
  "mmHeight"=>35,
  "mmWidth"=>25
);
$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 IDPhotoAPIExample {

    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 = "http(s)://api.shiliuai.com/api/id_photo/v1";

            // 请求参数 (初次请求)
            JSONObject requestData = new JSONObject();
            requestData.put("base64", photoBase64);
            requestData.put("bgColor", "FFFFFF");
            requestData.put("dpi", 300);
            requestData.put("mmHeight", 35);
            requestData.put("mmWidth", 25);

            // 发送 POST 请求
            JSONObject response = sendPostRequest(apiUrl, apiKey, requestData);

            // 检查响应是否成功
            if (response.getInt("code") == 0) {
                String resultBase64 = response.getString("result_base64");
                String id = response.getString("id");

                // 解码并保存图片
                byte[] resultBytes = Base64.getDecoder().decode(resultBase64);
                try (FileOutputStream fos = new FileOutputStream("result.jpg")) {
                    fos.write(resultBytes);
                }

                System.out.println("图片生成成功,文件已保存为 result.jpg");

                // 同一张图片,参数改变,再次请求
                JSONObject newRequestData = new JSONObject();
                newRequestData.put("id", id);
                newRequestData.put("bgColor", "FF0000");
                newRequestData.put("dpi", 300);
                newRequestData.put("pxHeight", 640);
                newRequestData.put("pxWidth", 480);

                // 发送新的请求
                JSONObject newResponse = sendPostRequest(apiUrl, apiKey, newRequestData);
                if (newResponse.getInt("code") == 0) {
                    String newResultBase64 = newResponse.getString("result_base64");
                    byte[] newResultBytes = Base64.getDecoder().decode(newResultBase64);
                    try (FileOutputStream fos = new FileOutputStream("result_red_bg.jpg")) {
                        fos.write(newResultBytes);
                    }
                    System.out.println("参数改变后的图片生成成功,文件已保存为 result_red_bg.jpg");
                } else {
                    System.out.println("新的请求失败: " + newResponse.getString("msg_cn"));
                }

            } 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 = 'http(s)://api.shiliuai.com/api/id_photo/v1';

    // 请求参数 (初次请求)
    const requestData = {
      base64: photoBase64,
      bgColor: "FFFFFF",
      dpi: 300,
      mmHeight: 35,
      mmWidth: 25
    };

    // 发送 POST 请求
    let response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'APIKEY': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    });

    let responseData = await response.json();

    // 检查响应是否成功
    if (responseData.code === 0) {
      const resultBase64 = responseData.result_base64;
      const id = responseData.id;

      // 解码并保存图片
      const resultBuffer = Buffer.from(resultBase64, 'base64');
      fs.writeFileSync('result.jpg', resultBuffer);
      console.log("图片生成成功,文件已保存为 result.jpg");

      // 同一张图片,参数改变,再次请求
      const newRequestData = {
        id: id,
        bgColor: "FF0000",
        dpi: 300,
        pxHeight: 640,
        pxWidth: 480
      };

      response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'APIKEY': apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(newRequestData)
      });

      responseData = await response.json();

      if (responseData.code === 0) {
        const newResultBase64 = responseData.result_base64;
        const newResultBuffer = Buffer.from(newResultBase64, 'base64');
        fs.writeFileSync('result_red_bg.jpg', newResultBuffer);
        console.log("参数改变后的图片生成成功,文件已保存为 result_red_bg.jpg");
      } else {
        console.error("新的请求失败:", responseData.msg_cn);
      }

    } else {
      console.error("初次请求失败:", responseData.msg_cn);
    }
  } catch (error) {
    console.error("发生错误:", error);
  }
})();

4.5 NodeJs

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

const apiKey = '******';
const filePath = 'path/to/your/image.jpg';
const apiUrl = 'http(s)://api.shiliuai.com/api/id_photo/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 photoBase64 = fs.readFileSync(filePath).toString('base64');

  post({
    base64: photoBase64,
    bgColor: "FFFFFF",
    dpi: 300,
    mmHeight: 35,
    mmWidth: 25
  }, 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({
      id: data.id,
      bgColor: "FF0000",
      dpi: 300,
      pxHeight: 640,
      pxWidth: 480
    }, function (error2, response2, body2) {
      if (error2) {
        console.error(error2);
        return;
      }
      let data2 = body2;
      try {
        if (typeof body2 === 'string') data2 = JSON.parse(body2);
      } catch (e) {}
      if (data2.code === 0) {
        fs.writeFileSync('result_red_bg.jpg', Buffer.from(data2.result_base64, 'base64'));
        console.log('参数改变后的图片生成成功,文件已保存为 result_red_bg.jpg');
      } else {
        console.error('新的请求失败:', data2.msg_cn || data2.msg);
      }
    });
  });
}

main();

4.6 cURL

# 初次请求(将图片转为 base64 后填入)
curl -k 'http(s)://api.shiliuai.com/api/id_photo/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"base64":"图片base64编码","bgColor":"FFFFFF","dpi":300,"mmHeight":35,"mmWidth":25}'

# 同一张图片,参数改变后再次请求(id 为初次返回的值)
curl -k 'http(s)://api.shiliuai.com/api/id_photo/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"id":"初次返回的id","bgColor":"FF0000","dpi":300,"pxHeight":640,"pxWidth":480}'

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()
    {
        var apiKey = "******";
        var filePath = "path/to/your/image.jpg";
        var url = "http(s)://api.shiliuai.com/api/id_photo/v1";

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

        var photoBase64 = Convert.ToBase64String(File.ReadAllBytes(filePath));

        var request1 = new
        {
            base64 = photoBase64,
            bgColor = "FFFFFF",
            dpi = 300,
            mmHeight = 35,
            mmWidth = 25
        };

        var json1 = JsonSerializer.Serialize(request1);
        var res1 = await client.PostAsync(url, new StringContent(json1, Encoding.UTF8, "application/json"));
        var body1 = await res1.Content.ReadAsStringAsync();

        using var doc1 = JsonDocument.Parse(body1);
        var root1 = doc1.RootElement;
        if (root1.GetProperty("code").GetInt32() != 0)
        {
            var msg = root1.TryGetProperty("msg_cn", out var msgCn) ? msgCn.GetString() : root1.GetProperty("msg").GetString();
            Console.WriteLine("初次请求失败: " + msg);
            return;
        }

        var resultBase64 = root1.GetProperty("result_base64").GetString();
        var id = root1.GetProperty("id").GetString();
        File.WriteAllBytes("result.jpg", Convert.FromBase64String(resultBase64));
        Console.WriteLine("图片生成成功,文件已保存为 result.jpg");

        var request2 = new
        {
            id = id,
            bgColor = "FF0000",
            dpi = 300,
            pxHeight = 640,
            pxWidth = 480
        };

        var json2 = JsonSerializer.Serialize(request2);
        var res2 = await client.PostAsync(url, new StringContent(json2, Encoding.UTF8, "application/json"));
        var body2 = await res2.Content.ReadAsStringAsync();

        using var doc2 = JsonDocument.Parse(body2);
        var root2 = doc2.RootElement;
        if (root2.GetProperty("code").GetInt32() != 0)
        {
            var msg = root2.TryGetProperty("msg_cn", out var msgCn) ? msgCn.GetString() : root2.GetProperty("msg").GetString();
            Console.WriteLine("二次请求失败: " + msg);
            return;
        }

        var resultBase642 = root2.GetProperty("result_base64").GetString();
        File.WriteAllBytes("result_red_bg.jpg", Convert.FromBase64String(resultBase642));
        Console.WriteLine("参数改变后的图片生成成功,文件已保存为 result_red_bg.jpg");
    }
}

4.8 易语言

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

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

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

4.9 天诺

public static string Api_IdPhoto(Image image, string apiKey)
{
    string url = "http(s)://api.shiliuai.com/api/id_photo/v1";
    var headers = new Dictionary
    {
        {"Authorization", "APPCODE " + appcode},
        {"Content-Type", "application/json"}
    };
    string body = "{\"base64\":\"" + CustomHelp.ImageTobase64(image) + "\",\"bgColor\":\"FFFFFF\",\"dpi\":300,\"mmHeight\":35,\"mmWidth\":25}";
    return CustomHelp.HttpPost(url, body, headers);
}

4.10 按键精灵-电脑版

Import "Encrypt.dll"

VBSBegin
' 启用错误处理
On Error Resume Next

Function Base64Encode(filePath)
    ' 检查文件是否存在
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(filePath) Then
        Base64Encode = "ERROR:FileNotFound"
        Exit Function
    End If

    Set inStream = CreateObject("ADODB.Stream")
    inStream.Type = 1 ' adTypeBinary
    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
    ' 清理对象
    Set inStream = Nothing
    Set dom = Nothing
    Set elem = Nothing
    Set fso = Nothing
End Function

Function api_id_photo(apiKey, imgPath)
    ' 先检查文件是否存在,避免后续错误
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(imgPath) Then
        api_id_photo = "ERROR: 图片文件不存在 - " & imgPath
        Exit Function
    End If

    ' 获取Base64并移除所有换行符(包括可能的回车换行)
    Dim base64Str
    base64Str = Base64Encode(imgPath)
    If Left(base64Str, 5) = "ERROR" Then
        api_id_photo = base64Str
        Exit Function
    End If

    ' 彻底清理换行和可能存在的空白字符
    base64Str = Replace(base64Str, vbCrLf, "")
    base64Str = Replace(base64Str, vbLf, "")
    base64Str = Replace(base64Str, vbCr, "")
    base64Str = Replace(base64Str, Chr(13), "")
    base64Str = Replace(base64Str, Chr(10), "")
    base64Str = Trim(base64Str) ' 去除首尾空白

    ' 构建JSON(使用CHR(34)避免引号冲突)
    Dim jsonBody
    jsonBody = "{" & Chr(34) & "base64" & Chr(34) & ":" & Chr(34) & base64Str & Chr(34) & "," & Chr(34) & "bgColor" & Chr(34) & ":" & Chr(34) & "FFFFFF" & Chr(34) & "," & Chr(34) & "dpi" & Chr(34) & ":300," & Chr(34) & "mmHeight" & Chr(34) & ":35," & Chr(34) & "mmWidth" & Chr(34) & ":25}"

    ' 创建HTTP对象
    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "POST", "http(s)://api.shiliuai.com/api/id_photo/v1", False
    http.setRequestHeader "APIKEY", apiKey
    http.setRequestHeader "Content-Type", "application/json"

    ' 发送请求
    On Error Resume Next ' 再次确保捕获网络错误
    http.send jsonBody

    If Err.Number <> 0 Then
        api_id_photo = "HTTP发送错误: " & Err.Description
        Err.Clear
        Exit Function
    End If

    ' 检查HTTP状态
    If http.Status <> 200 Then
        api_id_photo = "HTTP状态异常: " & http.Status & " - " & http.statusText
        Exit Function
    End If

    api_id_photo = http.responseText
    Set http = Nothing
    Set fso = Nothing
End Function
VBSEnd

' 主程序部分
apiKey = "你的APIKEY"   ' 请替换为真实APIKEY
imgPath = "你的图片路径.jpg"   ' 请替换为真实图片路径

res = api_id_photo(apiKey, imgPath)

' 输出结果,如果出错则显示错误信息
If Left(res, 5) = "ERROR" Or Left(res, 6) = "HTTP状态" Or Left(res, 5) = "HTTP发" Then
    TracePrint "【错误】" & res
Else
    TracePrint "【响应】" & res
End If

4.11 按键精灵-手机版

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

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

Function api_id_photo(apiKey, imagePath)
    Dim url = "http(s)://api.shiliuai.com/api/id_photo/v1"
    Dim body = "{""base64"":""" & yd.Base64EncodeFile(imagePath) & """,""bgColor"":""FFFFFF"",""dpi"":300,""mmHeight"":35,""mmWidth"":25}"
    Dim headers = {null}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    Dim res = yd.HttpPost(url, body, headers)
    api_id_photo = yd.JsonDecode(res)
End Function

Dim apiKey = "你的APIKEY"
Dim res = api_id_photo(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_id_photo(apiKey, imagePath)
    local url = "http(s)://api.shiliuai.com/api/id_photo/v1"
    local body = json.encode({ base64 = readFileBase64(imagePath), bgColor = 'FFFFFF', dpi = 300, mmHeight = 35, mmWidth = 25 })
    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_id_photo(apiKey, imagePath)
    local url = "http(s)://api.shiliuai.com/api/id_photo/v1"
    local body = jsonLib.encode({ base64 = getFileBase64(imagePath), bgColor = 'FFFFFF', dpi = 300, mmHeight = 35, mmWidth = 25 })
    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_id_photo(apiKey, img)
    logd(console.timeEnd("t"))
    logd(res.code)
end

function api_id_photo(apiKey, img)
    local url = "http(s)://api.shiliuai.com/api/id_photo/v1"
    local imgBase64 = image.toBase64Format(img, "jpg", 100)
    image.recycle(img)
    local body = JSON.stringify({ base64 = imgBase64, bgColor = 'FFFFFF', dpi = 300, mmHeight = 35, mmWidth = 25 })
    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