1.接口说明

图片转化 / 压缩 API:输入 Base64 图片或已有图片 ID,按需完成格式转换、DPI/宽高调整与压缩,返回结果 Base64(并返回新的 image_id)。

1.1主要功能

图片格式转换:
支持生成 JPEG / PNG / BMP。
分辨率与尺寸调整:
支持 DPI 调整,支持按像素设置宽度/高度。
质量压缩与大小约束:
支持 quality(1~100);当 quality 为空时,可使用 minFileSize/maxFileSize(单位:字节)进行目标大小约束压缩。
适配批量链路:
支持传 image_id,便于与其它接口串联与复用上传资源。

1.2接入场景

网站图片优化(体积更小/加载更快)、内容生产与素材管理、电商主图处理、移动端图片上传压缩、批量格式规范化等。

2.请求信息

2.1请求地址(URL)

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

2.2请求方式

POST

2.3请求头(header)

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

2.4请求体(body)

参数 是否必填 类型 说明
image_base64 必须填写其中之一 string base64 编码的图片文件(小于20M)
image_url string 图片文件url(小于20M)
image_id string 图片 id,对于已经请求过的图片,如果需要重复检测或更改参数,使用 id 而无需再上传 image_base64和image_url
dpi int [10, 1000],生成图片分辨率,默认不改变
width int 生成图片宽度(像素),默认不改变
height int 生成图片高度(像素),默认不改变
quality int [1, 100],生成图片质量,默认为 92
minFileSize int 生成图片最小文件大小(字节),仅当 quality 为空时生效;如 10240 表示 ≥10KB
maxFileSize int 生成图片最大文件大小(字节),仅当 quality 为空时生效
format string 生成图片格式:"JPEG" / "PNG" / "BMP"

3.返回信息

3.1返回类型

JSON

3.2返回字段

参数 说明
code 错误码
msg 错误信息(英文)
msg_cn 错误信息(中文)
result_base64 转换/压缩后的图片 base64(当 code==0 时返回)
image_id 图片 id(当 code==0 时返回)

3.3返回示例

{
  "code": 0,
  "msg": "OK",
  "msg_cn": "成功",
  "image_id": "xxxxxx",
  "result_base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}

3.4错误码

错误码 说明
0成功
1图片错误
2处理错误
3服务器繁忙
4参数错误(具体错误看 msg 或 msg_cn)
5未知错误
101API-KEY 不正确
102未知用户
103积分已用完
104扣除积分失败

4.示例代码

4.1 Python

# -*- coding: utf-8 -*-
import requests
import base64
import json

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/image_convert/v1'
headers = {'APIKEY': api_key, "Content-Type": "application/json"}
data = {
    "image_base64": photo_base64,
    "dpi": 300
}

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}
失败:{'code': error_code, 'msg': error_msg, 'msg_cn': 错误信息}
"""

result_base64 = response['result_base64']
file_bytes = base64.b64decode(result_base64)
with open('result.jpg', 'wb') as f:
    f.write(file_bytes)

4.2 PHP

<?php
$url = "https://api.shiliuai.com/api/image_convert/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,
    "dpi" => 300
);
$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 JavaScript

const fs = require('fs');

const apiKey = '******';
const filePath = '...';
const apiUrl = 'https://api.shiliuai.com/api/image_convert/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, dpi: 300 })
  });

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

4.4 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/image_convert/v1";

        // 将图片编码为Base64
        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,
            dpi = 300
        };
        string jsonData = JsonSerializer.Serialize(requestData);

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("APIKEY", apiKey);
            client.DefaultRequestHeaders.Add("Content-Type", "application/json");

            try
            {
                // 发送POST请求
                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);

                int code = responseObject.GetProperty("code").GetInt32();
                if (code == 0)
                {
                    string resultBase64 = responseObject.GetProperty("result_base64").GetString();
                    
                    // 将Base64转换为图片并保存
                    byte[] fileBytes = Convert.FromBase64String(resultBase64);
                    File.WriteAllBytes("result.jpg", fileBytes);
                    Console.WriteLine("Image processing succeeded, saved as result.jpg");
                }
                else
                {
                    string errorMsg = responseObject.GetProperty("msg_cn").GetString();
                    Console.WriteLine($"Error: {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }
    }
}

4.5 易语言

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

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

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

4.6 天诺

public static string Api_Image64Dpi(Image image, string apiKey)
{
    string url = "https://api.shiliuai.com/api/image_convert/v1";
    var headers = new Dictionary
    {
        {"Authorization", "APPCODE " + appcode},
        {"Content-Type", "application/json"}
    };
    string body = "{\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\",\"dpi\":300}";
    return CustomHelp.HttpPost(url, body, headers);
}

4.7 按键精灵-电脑版

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_image64_dpi(apiKey, imgPath)
    url = "https://api.shiliuai.com/api/image_convert/v1"
    jsonBody = "{""image_base64"":""" & Base64Encode(imgPath) & """,""dpi"":300}"
    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_dpi = http.responseText
End Function
VBSEnd

apiKey = "你的APIKEY"
res = api_image64_dpi(apiKey, "你的图片路径.jpg")
TracePrint res

4.8 按键精灵-手机版

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

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

Function api_image64_dpi(apiKey, imagePath)
    Dim url = "https://api.shiliuai.com/api/image_convert/v1"
    Dim body = "{""image_base64"":""" & yd.Base64EncodeFile(imagePath) & """,""dpi"":300}"
    Dim headers = {null}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    Dim res = yd.HttpPost(url, body, headers)
    api_image64_dpi = yd.JsonDecode(res)
End Function

Dim apiKey = "你的APIKEY"
Dim res = api_image64_dpi(apiKey, imagePath)
TracePrint res["code"]

4.9 触动精灵

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_dpi(apiKey, imagePath)
    local url = "https://api.shiliuai.com/api/image_convert/v1"
    local body = json.encode({ image_base64 = readFileBase64(imagePath), dpi = 300 })
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local resp = httpPost(url, body, { headers = headers })
    return json.decode(resp)
end

4.10 懒人精灵

function api_image64_dpi(apiKey, imagePath)
    local url = "https://api.shiliuai.com/api/image_convert/v1"
    local body = jsonLib.encode({ image_base64 = getFileBase64(imagePath), dpi = 300 })
    local headers = {}
    headers["APIKEY"] = apiKey
    headers["Content-Type"] = "application/json"
    local resp = httpPost(url, body, { headers = headers })
    return jsonLib.decode(resp)
end

4.11 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_dpi(apiKey, img)
    logd(console.timeEnd("t"))
    logd(res.code)
end

function api_image64_dpi(apiKey, img)
    local url = "https://api.shiliuai.com/api/image_convert/v1"
    local imgBase64 = image.toBase64Format(img, "jpg", 100)
    image.recycle(img)
    local body = JSON.stringify({ image_base64 = imgBase64, dpi = 300 })
    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