响应格式
默认(response=json)
{
"success": true,
"data": "Base64编码的图片数据",
"format": "image/webp",
"originalSize": 1024000,
"compressedSize": 204800,
"compressionRatio": 80
}
响应字段说明
| 字段名 |
类型 |
说明 |
| success |
Boolean |
请求是否成功 |
| data |
String |
Base64编码的压缩后图片数据 |
| format |
String |
输出图片的MIME类型 |
| originalSize |
Integer |
原始图片大小(字节) |
| compressedSize |
Integer |
压缩后图片大小(字节) |
| compressionRatio |
Integer |
压缩率(百分比) |
二进制响应(response=binary)
响应体直接为压缩后的图片二进制数据,不做 Base64 编码。图片的元信息通过响应头返回:
| 响应头 |
说明 |
| Content-Type |
压缩后的 MIME 类型(如 image/webp) |
| Content-Length |
压缩后的字节数 |
| X-Original-Size |
原图大小(字节) |
| X-Compressed-Size |
压缩后大小(字节) |
| X-Compression-Ratio |
压缩率(百分比) |
| X-Format |
压缩后 MIME 类型 |
| X-File-Name |
原始文件名(URL 编码) |
使用示例
JavaScript示例
// 使用FormData发送请求
const formData = new FormData();
formData.append('image', imageFile);
formData.append('quality', 80);
formData.append('outputFormat', 'webp');
const response = await fetch('https://compress.scdn.io/api/compress.php', {
method: 'POST',
body: formData
});
const result = await response.json();
// 使用压缩后的图片
const compressedImage = `data:${result.format};base64,${result.data}`;
将GIF动图压缩为WebP动图
// 同样使用FormData发送请求
const formData = new FormData();
formData.append('image', gifFile); // gifFile 是一个GIF动图文件
formData.append('quality', 75);
formData.append('outputFormat', 'webp_animated');
const response = await fetch('https://compress.scdn.io/api/compress.php', {
method: 'POST',
body: formData
});
const result = await response.json();
// result.format 将会是 "image/webp"
const animatedWebpImage = `data:${result.format};base64,${result.data}`;
PHP示例
// 使用cURL发送请求
$ch = curl_init('https://compress.scdn.io/api/compress.php');
$data = [
'image' => new CURLFile('path/to/image.jpg'),
'quality' => 80,
'outputFormat' => 'webp'
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result = json_decode($response, true);
直接获取二进制数据(response=binary)
// JavaScript:直接拿到 Blob,无需 Base64 解码
const formData = new FormData();
formData.append('image', imageFile);
formData.append('outputFormat', 'webp');
formData.append('response', 'binary');
const response = await fetch('https://compress.scdn.io/api/compress.php', {
method: 'POST',
body: formData
});
const originalSize = Number(response.headers.get('X-Original-Size'));
const compressedSize = Number(response.headers.get('X-Compressed-Size'));
const blob = await response.blob();
const compressedUrl = URL.createObjectURL(blob);
# cURL:把压缩结果直接写入文件
curl -X POST \
-F "image=@/path/to/image.jpg" \
-F "outputFormat=webp" \
-F "response=binary" \
-o compressed.webp \
https://compress.scdn.io/api/compress.php