图片水印裁剪缩略接口实战:用 width/height/x/y 精确裁剪图片区域
# 图片水印裁剪缩略接口实战:用 width/height/x/y 精确裁剪图片区域
> 接口/接入点:图片水印裁剪缩略接口(apiCode=1)· 1-4 图像裁剪-base64 · 是否免费:免费 · 请求方式:POST/GET · 返回格式:JSON · 适用人群:前端、全栈 · 阅读时间:6 分钟
## 核心要点
- 1-4 按「左上角起点 (x,y) + 宽高 (width,height)」截取矩形区域。
- `width`、`height` **必填**;`x`、`y` 可选(默认从 0,0 起);`src_img_base64` 必填。
- 坐标超出原图范围可能裁剪异常,调用前先校验边界。
## Why:什么时候要精确裁剪
头像截取、商品图抠出主体、证件区域提取——这些都要从大图里切出一块。1-4 用像素坐标直接裁,配合前端裁剪框(如 cropper.js)体验最好。
## What:参数速览
| 参数 | 必填 | 说明 |
|------|------|------|
| `width` | 是 | 裁剪后宽度(px) |
| `height` | 是 | 裁剪后高度(px) |
| `x` | 否 | 从 x 轴哪个坐标点开始(默认 0) |
| `y` | 否 | 从 y 轴哪个坐标点开始(默认 0) |
| `src_img_base64` | 是 | 原图 base64 字符串 |
坐标系(原点在左上角,向右 x 增大、向下 y 增大):
```
(0,0)───x──►
│ ┌──────────┐
y │ crop box │ width
│ │ (x,y) │ height
▼ └──────────┘
```
## How:裁剪头像区域
**Python(requests)**
```python
import requests, base64
with open("photo.jpg", "rb") as f:
b64 = base64.b64encode(f.read()).decode()
url = "https://route.showapi.com/1-4"
data = {
"width": "200", "height": "200",
"x": "100", "y": "100", # 从 (100,100) 起裁 200x200
"src_img_base64": b64,
}
r = requests.post(url, params={"appKey": "YOUR_APPKEY"}, data=data, timeout=10)
body = r.json()["showapi_res_body"]
if str(body.get("ret_code")) == "0":
print("裁剪图:", body["des_pic_url"])
```
**cURL**
```bash
curl -X POST "https://route.showapi.com/1-4?appKey=YOUR_APPKEY" \
-H "content-type: application/x-www-form-urlencoded" \
--data-urlencode "width=200" --data-urlencode "height=200" \
--data-urlencode "x=100" --data-urlencode "y=100" \
--data-urlencode "src_img_base64=【原图base64】"
```
**Node.js(fetch)**
```javascript
import fs from "fs";
const b64 = fs.readFileSync("photo.jpg").toString("base64");
const body = new URLSearchParams({ width:"200", height:"200", x:"100", y:"100", src_img_base64:b64 });
const res = await fetch("https://route.showapi.com/1-4?appKey=YOUR_APPKEY", {method:"POST", body});
const b = (await res.json()).showapi_res_body;
if (String(b.ret_code) === "0") console.log("裁剪图:", b.des_pic_url);
```
## 返回示例
```json
{ "showapi_res_body": { "des_pic_url": "http://img.showapi.com/1.jpg" } }
```
## 进阶/边界
- `x+width` 或 `y+height` 超过原图尺寸可能失败,前端裁剪框应做边界 clamp。
- 只想要缩略而非裁剪,用 1-1/1-5;想要水印用 1-2/1-3(见[base64 选型篇](https://www.showapi.com/guides/base64-vs-file-1))。
## FAQ
**Q1:x/y 不传会怎样?** 默认从 (0,0) 起裁,等于裁左上角区域。
**Q2:base64 太大报错?** 免费接口有体积档位限制;先压缩原图或走文件版 1-2(需水印)再裁剪。
**Q3:返回没有 ret_code?** 以返回体 schema 为准,`ret_code` 属于 `showapi_res_body`;失败看 `showapi_res_error`。
**Q4:想裁完加水印?** 先 1-4 裁,再拿结果图做 1-2/1-3 水印,分步调用。
## 相关能力 / 下一步阅读
- [图片水印裁剪缩略接口:base64 与文件上传两种入参怎么选](https://www.showapi.com/guides/base64-vs-file-1)
- [图片水印裁剪缩略接口:5 分钟生成第一张缩略图](https://www.showapi.com/guides/image-thumbnail-quickstart-1)
- **本系列共 13 篇**:查看[图片水印裁剪缩略接口指南总目录](https://www.showapi.com/guides/image-process-guides-1)