1.接口说明

人像变清晰 API:对人像照片进行清晰化与细节增强,输出增强后的图片(Base64)。

1.1主要功能

人像增强:
对人脸与皮肤细节进行增强,提升整体观感。
多输入方式:
支持 base64 图片或图片 URL(二选一)。
输出保持通道:
如果输入图片是四通道,将返回四通道 PNG;否则返回 JPG,输出通道数与输入一致。

1.2接入场景

人像照片修复、证件照增强、自拍照片清晰化、人像素材制作、社交媒体图片优化、内容生产与人像素材增强等。

2.请求信息

2.1请求地址(URL)

POST https://api.shiliuai.com/api/face_enhance/v1

2.2请求方式

POST

2.3请求头(header)

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

2.4请求体(body)

参数 是否必填 类型 说明
同步或异步提交任务
image_base64 必填其一 string 图片文件的base64编码,图片可以是单通道,三通道或四通道, 图片文件要小于20M,图片的长边不能超过2048像素
image_url string 图片的url,图片可以是单通道,三通道或四通道, 图片文件要小于20M,图片的长边不能超过2048像素
mode string 任务提交模式,"sync"表示同步,"async"表示异步,默认为同步
异步获取结果
mode string "async"
image_id string 异步提交任务返回的image_id

3.返回信息

3.1返回类型

JSON

3.2返回字段

参数 说明
request_id 请求id
code 错误码
msg 错误信息(英文)
msg_cn 错误信息(中文)
image_id 图片id,可用于异步获取结果
同步模式
result_base64 清晰图片的base64编码,(当code==0时会有该返回值), 如果输入图片是四通道,那么返回四通道png格式图片,否则返回jpg格式图片, 返回图片通道数和输入图片相同
异步模式
status 任务状态,added:已加入,processing:正在处理,done:处理完成
wait_time 大概还需等待时间,例如:1.2(秒)
result_base64 清晰图片的base64编码,当status为done时,有该返回值

3.3返回示例

// 同步成功
{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "b6a0f7d0b2f54d0ea3...",
  "result_base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}

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

// 异步轮询 - 处理完成
{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "b6a0f7d0b2f54d0ea3...",
  "status": "done",
  "result_base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}

3.4错误码

错误码 说明
0 成功
1 图片错误
2 处理错误
3 服务器繁忙
4 参数错误,具体错误看 msg 或 msg_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
file_path = '...'  # 图片路径

with open(file_path, 'rb') as fp:
    photo_base64 = base64.b64encode(fp.read()).decode('utf8')

url = 'https://api.shiliuai.com/api/face_enhance/v1'
headers = {'APIKEY': api_key, "Content-Type": "application/json"}
data = {
    "image_base64": photo_base64
}

response = requests.post(url=url, headers=headers, json=data)
response = json.loads(response.content)
"""
成功:{'code': 0, 'msg': 'OK', 'msg_cn': '成功', 'image_id': image_id, 'result_base64': result_base64}
or
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息, 'image_id': image_id}
"""
result_base64 = response['result_base64']
file_bytes = base64.b64decode(result_base64)
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_UNCHANGED)
cv2.imshow('result', image)
cv2.waitKey(0)
# -*- coding: utf-8 -*-
import time
import requests
import base64
import cv2
import json
import numpy as np

api_key = '******'  # 你的API KEY
file_path = '../data/man.jpg'  # 图片路径

with open(file_path, 'rb') as fp:
    photo_base64 = base64.b64encode(fp.read()).decode('utf8')

url = 'https://api.shiliuai.com/api/face_enhance/v1'
headers = {'APIKEY': api_key, "Content-Type": "application/json"}
data = {
    "mode": "async",
    "image_base64": photo_base64
}

response = requests.post(url=url, headers=headers, json=data)
response = json.loads(response.content)
"""
成功:{'code': 0, 'msg': 'OK', 'msg_cn': '成功', 'image_id': image_id, 'status': 'added', 'wait_time': 1.2}
or
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息, 'image_id': image_id}
"""

code = response.get('code')
image_id = response.get('image_id')

# 轮询获取结果
while True:
    wait_time = response.get('wait_time')
    time.sleep(wait_time)

    data = {
        "mode": "async",
        "image_id": image_id
    }
    response = requests.post(url=url, headers=headers, json=data)
    response = json.loads(response.content)
    status = response.get('status')

    if status == 'done':
        # 已完成
        result_base64 = response['result_base64']
        file_bytes = base64.b64decode(result_base64)
        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_UNCHANGED)
        cv2.imshow('result', image)
        cv2.waitKey(0)

        break

4.2 PHP

<?php
$url = "https://api.shiliuai.com/api/face_enhance/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(
  "image_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);
$response = json_decode($response, true);
if ($response['code'] == 0) {
  file_put_contents('result.jpg', base64_decode($response['result_base64']));
}
var_dump($response);
<?php
$url = "https://api.shiliuai.com/api/face_enhance/v1";
$method = "POST";
$apikey = "******";
$header = array();
array_push($header, "APIKEY:" . $apikey);
array_push($header, "Content-Type:application/json");

$file_path = "../data/man.jpg";
$handle = fopen($file_path, "r");
$photo = fread($handle, filesize($file_path));
fclose($handle);
$photo_base64 = base64_encode($photo);

$data = array(
  "mode"=> "async",
  "image_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);
$response = json_decode($response, true);
$image_id = $response['image_id'];

while (true) {
  $wait_time = isset($response['wait_time']) ? $response['wait_time'] : 1;
  sleep((int)$wait_time);

  $data = array(
    "mode"=> "async",
    "image_id"=> $image_id
  );
  $post_data = json_encode($data);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
  $response = curl_exec($curl);
  $response = json_decode($response, true);

  if (isset($response['status']) && $response['status'] === 'done') {
    file_put_contents('result.jpg', base64_decode($response['result_base64']));
    break;
  }
}
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 FaceEnhanceApiExample {
    public static void main(String[] args) {
        String apiKey = "******";
        String filePath = "...";
        String apiUrl = "https://api.shiliuai.com/api/face_enhance/v1";

        try {
            String imageBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(new File(filePath).toPath()));
            JSONObject requestData = new JSONObject();
            requestData.put("image_base64", imageBase64);

            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());
    }
}
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 FaceEnhanceApiExampleAsync {
    public static void main(String[] args) {
        String apiKey = "******";
        String filePath = "../data/man.jpg";
        String apiUrl = "https://api.shiliuai.com/api/face_enhance/v1";

        try {
            String imageBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(new File(filePath).toPath()));
            JSONObject requestData = new JSONObject();
            requestData.put("mode", "async");
            requestData.put("image_base64", imageBase64);

            JSONObject response = sendPost(apiUrl, apiKey, requestData);
            String imageId = response.getString("image_id");

            while (true) {
                double waitTime = response.optDouble("wait_time", 1.0);
                Thread.sleep((long) (waitTime * 1000));

                JSONObject pollData = new JSONObject();
                pollData.put("mode", "async");
                pollData.put("image_id", imageId);
                response = sendPost(apiUrl, apiKey, pollData);

                if ("done".equals(response.optString("status"))) {
                    byte[] resultBytes = Base64.getDecoder().decode(response.getString("result_base64"));
                    Files.write(new File("result.jpg").toPath(), resultBytes);
                    System.out.println("人像变清晰成功,已保存 result.jpg");
                    break;
                }
            }
        } 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 filePath = '...';
const apiUrl = 'https://api.shiliuai.com/api/face_enhance/v1';

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

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

  const data = await res.json();
  if (data.code === 0) {
    fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
    console.log('人像变清晰成功,已保存 result.jpg');
  } else {
    console.error('请求失败:', data.msg_cn || data.msg);
  }
}

main().catch(console.error);
const fs = require('fs');

const apiKey = '******';
const filePath = '../data/man.jpg';
const apiUrl = 'https://api.shiliuai.com/api/face_enhance/v1';

function sleep(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}

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

  let res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      APIKEY: apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ mode: "async", image_base64: imageBase64 })
  });

  let data = await res.json();
  const imageId = data.image_id;

  while (true) {
    await sleep(data.wait_time || 1);

    res = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        APIKEY: apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ mode: 'async', image_id: imageId })
    });

    data = await res.json();
    if (data.status === 'done') {
      fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
      console.log('人像变清晰成功,已保存 result.jpg');
      break;
    }
  }
}

main().catch(console.error);

4.5 NodeJs

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

const apiKey = '******';
const filePath = '...';
const apiUrl = 'https://api.shiliuai.com/api/face_enhance/v1';

function main() {
  const fileBase64 = fs.readFileSync(filePath).toString('base64');
  const options = {
    method: "POST",
    url: apiUrl,
    headers: {
      APIKEY: apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ image_base64: fileBase64 }),
  };

  request(options, 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) {
      fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
      console.log('人像变清晰成功,已保存 result.jpg');
    } else {
      console.error('请求失败:', data.msg_cn || data.msg);
    }
  });
}

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

const apiKey = '******';
const filePath = '../data/man.jpg';
const apiUrl = 'https://api.shiliuai.com/api/face_enhance/v1';

function sleep(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}

function post(options) {
  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) return reject(error);
      let data = body;
      try {
        if (typeof body === 'string') data = JSON.parse(body);
      } catch (e) {}
      resolve(data);
    });
  });
}

async function main() {
  const fileBase64 = fs.readFileSync(filePath).toString('base64');

  let data = await post({
    method: "POST",
    url: apiUrl,
    headers: {
      APIKEY: apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ mode: "async", image_base64: fileBase64 }),
  });

  const imageId = data.image_id;

  while (true) {
    await sleep(data.wait_time || 1);

    data = await post({
      method: "POST",
      url: apiUrl,
      headers: {
        APIKEY: apiKey,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ mode: "async", image_id: imageId }),
    });

    if (data.status === 'done') {
      fs.writeFileSync('result.jpg', Buffer.from(data.result_base64, 'base64'));
      console.log('人像变清晰成功,已保存 result.jpg');
      break;
    }
  }
}

main().catch(console.error);

4.6 cURL

# 将图片转为 base64 后填入请求体(Linux/macOS 示例)
# IMAGE_BASE64=$(base64 -w 0 /path/to/image.jpg)

curl -k 'https://api.shiliuai.com/api/face_enhance/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"image_base64":"图片base64编码"}'
# 1. 提交异步任务
curl -k 'https://api.shiliuai.com/api/face_enhance/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"mode":"async","image_base64":"图片base64编码"}'

# 2. 轮询结果(将 image_id 替换为上一步返回的值)
curl -k 'https://api.shiliuai.com/api/face_enhance/v1' \
  -H 'APIKEY: 你的APIKEY' \
  -H 'Content-Type: application/json' \
  -d '{"mode":"async","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 = "https://api.shiliuai.com/api/face_enhance/v1";

        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);
            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);

            if (responseObject.GetProperty("code").GetInt32() == 0)
            {
                string resultBase64 = responseObject.GetProperty("result_base64").GetString();
                byte[] fileBytes = Convert.FromBase64String(resultBase64);
                File.WriteAllBytes("result.jpg", fileBytes);
                Console.WriteLine("人像变清晰成功,已保存 result.jpg");
            }
        }
    }
}
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 = "******";
        string filePath = "../data/man.jpg";
        string url = "https://api.shiliuai.com/api/face_enhance/v1";

        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);
        }

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

            var submitData = new
            {
            mode = "async",
            image_base64 = photoBase64
            };
            var response = await client.PostAsync(url, new StringContent(JsonSerializer.Serialize(submitData), Encoding.UTF8, "application/json"));
            var responseObject = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
            string imageId = responseObject.GetProperty("image_id").GetString();

            while (true)
            {
                double waitTime = responseObject.TryGetProperty("wait_time", out var wt) ? wt.GetDouble() : 1.0;
                await Task.Delay((int)(waitTime * 1000));

                var pollData = new { mode = "async", image_id = imageId };
                response = await client.PostAsync(url, new StringContent(JsonSerializer.Serialize(pollData), Encoding.UTF8, "application/json"));
                responseObject = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());

                if (responseObject.GetProperty("status").GetString() == "done")
                {
                    string resultBase64 = responseObject.GetProperty("result_base64").GetString();
                    File.WriteAllBytes("result.jpg", Convert.FromBase64String(resultBase64));
                    Console.WriteLine("人像变清晰成功,已保存 result.jpg");
                    break;
                }
            }
        }
    }
}

4.8 易语言

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

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

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

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

图片数据 = 读入文件 ("你的图片路径.jpg")
base64图片 = 编码_BASE64编码 (图片数据)
局_提交数据 = "{" + #引号 + "mode" + #引号 + ":" + #引号 + "async" + #引号 + "," + #引号 + "image_base64" + #引号 + ":" + #引号 + base64图片 + #引号 + "}"
局_网址 = "https://api.shiliuai.com/api/face_enhance/v1"
局_方式 = 1
局_提交协议头 = "APIKEY: 你的APIKEY" + #换行符 + "Content-Type: application/json"
局_结果 = 网页_访问_对象 (局_网址, 局_方式, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
' 解析 image_id、wait_time 后循环轮询
.判断循环 (真)
    程序_延时 (wait_time × 1000, )
    局_提交数据 = "{" + #引号 + "mode" + #引号 + ":" + #引号 + "async" + #引号 + "," + #引号 + "image_id" + #引号 + ":" + #引号 + image_id + #引号 + "}"
    局_结果 = 网页_访问_对象 (局_网址, 局_方式, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
    局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
    ' status 为 done 时保存 result_base64
.判断循环结束 ()
返回 (局_返回)

4.9 天诺

public static string Api_Image64(Image image, string apiKey)
{
    string url = "https://api.shiliuai.com/api/face_enhance/v1";
    var headers = new Dictionary<string, string>
    {
        {"Authorization", "APPCODE " + appcode},
        {"Content-Type", "application/json"}
    };
    string body = "{\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
    return CustomHelp.HttpPost(url, body, headers);
}
public static string Api_Image64Async(Image image, string apiKey)
{
    string url = "https://api.shiliuai.com/api/face_enhance/v1";
    var headers = new Dictionary<string, string>
    {
        {"Authorization", "APPCODE " + appcode},
        {"Content-Type", "application/json"}
    };
    string body = "{\"mode\":\"async\",\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
    string response = CustomHelp.HttpPost(url, body, headers);
    // 解析 image_id,按 wait_time 轮询
    string pollBody = "{\"mode\":\"async\",\"image_id\":\"...\"}";
    while (true)
    {
        Thread.Sleep(1200);
        response = CustomHelp.HttpPost(url, pollBody, headers);
        // status 为 done 时返回 result_base64
    }
    return response;
}

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
End Function

Function api_image64(apiKey, imgPath)
    url = "https://api.shiliuai.com/api/face_enhance/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
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
End Function

Function api_image64Async(apiKey, imgPath)
    url = "https://api.shiliuai.com/api/face_enhance/v1"
    jsonBody = "{""mode"":""async"",""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
    responseText = http.responseText
    ' 解析 image_id
    Do
        WScript.Sleep 1200
        jsonBody = "{""mode"":""async"",""image_id"":""...""}"
        http.send jsonBody
        responseText = http.responseText
        ' status 为 done 时结束
    Loop
    api_image64Async = responseText
End Function
VBSEnd

apiKey = "你的APIKEY"
res = api_image64Async(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 = "https://api.shiliuai.com/api/face_enhance/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"]
Import "yd.luae"
Import "zm.luae"

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

Function api_image64Async(apiKey, imagePath)
    Dim url = "https://api.shiliuai.com/api/face_enhance/v1"
    Dim body = "{""mode"":""async"",""image_base64"":""" & yd.Base64EncodeFile(imagePath) & ""}"
    Dim headers = {null}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    Dim res = yd.HttpPost(url, body, headers)
    Dim data = yd.JsonDecode(res)
    Dim imageId = data["image_id"]
    Do
        Delay data["wait_time"] * 1000
        body = "{""mode"":""async"",""image_id"":""" & imageId & """}"
        res = yd.HttpPost(url, body, headers)
        data = yd.JsonDecode(res)
    Loop While data["status"] <> "done"
    api_image64Async = data
End Function

Dim apiKey = "你的APIKEY"
Dim res = api_image64Async(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 = "https://api.shiliuai.com/api/face_enhance/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
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_image64Async(apiKey, imagePath)
    local url = "https://api.shiliuai.com/api/face_enhance/v1"
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local body = json.encode({ mode = "async", image_base64 = readFileBase64(imagePath) })
    local resp = httpPost(url, body, { headers = headers })
    local data = json.decode(resp)
    local imageId = data.image_id
    while true do
        mSleep((data.wait_time or 1) * 1000)
        body = json.encode({ mode = "async", image_id = imageId })
        resp = httpPost(url, body, { headers = headers })
        data = json.decode(resp)
        if data.status == "done" then
            return data
        end
    end
end

4.13 懒人精灵

function api_image64(apiKey, imagePath)
    local url = "https://api.shiliuai.com/api/face_enhance/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
function api_image64Async(apiKey, imagePath)
    local url = "https://api.shiliuai.com/api/face_enhance/v1"
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local body = jsonLib.encode({ mode = "async", image_base64 = getFileBase64(imagePath) })
    local resp = httpPost(url, body, { headers = headers })
    local data = jsonLib.decode(resp)
    local imageId = data.image_id
    while true do
        sleep((data.wait_time or 1) * 1000)
        body = jsonLib.encode({ mode = "async", image_id = imageId })
        resp = httpPost(url, body, { headers = headers })
        data = jsonLib.decode(resp)
        if data.status == "done" then
            return data
        end
    end
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 = "https://api.shiliuai.com/api/face_enhance/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
function main()
    local apiKey = "你的APIKEY"
    local img = image.captureFullScreenEx()
    local res = api_image64Async(apiKey, img)
    logd(res.status)
end

function api_image64Async(apiKey, img)
    local url = "https://api.shiliuai.com/api/face_enhance/v1"
    local imgBase64 = image.toBase64Format(img, "jpg", 100)
    image.recycle(img)
    local body = JSON.stringify({ mode = "async", image_base64 = imgBase64 })
    local params = {
        url = url,
        method = "POST",
        headers = {
            ["APIKEY"] = apiKey,
            ["Content-Type"] = "application/json"
        },
        requestBody = body
    }
    local res = http.request(params)
    local data = JSON.parse(res.body)
    local imageId = data.image_id
    while true do
        sleep((data.wait_time or 1) * 1000)
        body = JSON.stringify({ mode = "async", image_id = imageId })
        params.requestBody = body
        res = http.request(params)
        data = JSON.parse(res.body)
        if data.status == "done" then
            return data
        end
    end
end