- 博客
- 去水印 API 接入指南:开发者集成手册
去水印 API 接入指南:开发者集成手册
去水印 API 接入指南:开发者集成手册
如果你正在开发需要批量处理水印的应用、网站或自动化流程,API 集成是最佳选择。这是去水印项目第一篇面向开发者的技术文档。
sora2watermarkremover.net 提供去水印 API 接口,支持图片和视频的水印去除,可通过 HTTP 请求直接调用。本文介绍 API 接入流程、批量处理方案以及 Python/JavaScript 脚本集成方法。
API 概述
核心能力
- 图片去水印:支持 JPEG、PNG 格式,自动检测并去除水印
- 视频去水印:支持 MP4、MOV 格式,AI 自动识别水印位置
- 1080p 输出:处理后保持高清画质
- 最大 200MB:支持大文件处理
- 批量并发:支持多任务并行处理
定价
- 图片去水印:$0.04/张起
- 视频去水印:$0.5/视频起
- 新用户:10 条免费额度
API 接入流程
第一步:注册并获取 API Key
- 访问 sora2watermarkremover.net 注册账号
- 进入账户设置页面
- 找到 API 管理区域
- 生成 API Key(保持密钥安全,不要提交到公共代码仓库)
第二步:了解 API 端点
| 功能 | 端点 | 方法 | 说明 |
|---|---|---|---|
| 图片去水印 | /api/v1/image/remove-watermark | POST | 上传图片并去除水印 |
| 视频去水印 | /api/v1/video/remove-watermark | POST | 上传视频并去除水印 |
| 查询任务状态 | /api/v1/task/{task_id} | GET | 查询处理任务状态 |
| 下载结果 | /api/v1/task/{task_id}/download | GET | 下载处理结果 |
| 查询账户余额 | /api/v1/account/credits | GET | 查询剩余额度 |
第三步:请求格式
所有 API 请求需要携带以下 Header:
Content-Type: multipart/form-data(上传) 或 application/json
Authorization: Bearer YOUR_API_KEY
Python 脚本集成
安装依赖
pip install requests
图片去水印脚本
import requests
import os
API_KEY = "your_api_key_here"
BASE_URL = "https://sora2watermarkremover.net/api/v1"
def remove_watermark_from_image(image_path, output_path=None):
"""去除图片水印"""
# 上传图片
headers = {"Authorization": f"Bearer {API_KEY}"}
with open(image_path, 'rb') as f:
files = {'file': (os.path.basename(image_path), f, 'image/jpeg')}
response = requests.post(
f"{BASE_URL}/image/remove-watermark",
headers=headers,
files=files,
data={'mode': 'auto'} # auto 或 manual
)
task = response.json()
task_id = task['task_id']
print(f"任务已提交: {task_id}")
# 轮询等待处理完成
while True:
status_response = requests.get(
f"{BASE_URL}/task/{task_id}",
headers=headers
)
status = status_response.json()['status']
if status == 'completed':
# 下载结果
download_response = requests.get(
f"{BASE_URL}/task/{task_id}/download",
headers=headers,
stream=True
)
save_path = output_path or image_path.replace('.jpg', '_clean.jpg')
with open(save_path, 'wb') as f:
for chunk in download_response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"处理完成,已保存到: {save_path}")
break
elif status == 'failed':
print(f"处理失败: {status_response.json()['error']}")
break
else:
print(f"处理中... 状态: {status}")
import time
time.sleep(3)
# 使用示例
remove_watermark_from_image("watermarked_photo.jpg")
批量图片去水印脚本
import os
import glob
from remove_watermark import remove_watermark_from_image # 假设上面的函数在独立模块中
def batch_remove_watermarks(input_dir, output_dir):
"""批量去除目录下所有图片的水印"""
os.makedirs(output_dir, exist_ok=True)
images = glob.glob(os.path.join(input_dir, "*.jpg")) + \
glob.glob(os.path.join(input_dir, "*.png"))
for i, image_path in enumerate(images):
filename = os.path.basename(image_path)
output_path = os.path.join(output_dir, f"clean_{filename}")
print(f"[{i+1}/{len(images)}] 处理: {filename}")
try:
remove_watermark_from_image(image_path, output_path)
except Exception as e:
print(f"处理失败 {filename}: {e}")
print(f"批量处理完成,共 {len(images)} 张图片")
# 使用示例
batch_remove_watermarks("./input_photos/", "./output_photos/")
视频去水印脚本
import requests
import os
import time
def remove_watermark_from_video(video_path, output_path=None):
"""去除视频水印"""
headers = {"Authorization": f"Bearer {API_KEY}"}
with open(video_path, 'rb') as f:
files = {'file': (os.path.basename(video_path), f, 'video/mp4')}
response = requests.post(
f"{BASE_URL}/video/remove-watermark",
headers=headers,
files=files,
data={'mode': 'auto'}
)
task = response.json()
task_id = task['task_id']
print(f"视频处理任务已提交: {task_id}")
# 视频处理时间较长,增加轮询间隔
while True:
status_response = requests.get(
f"{BASE_URL}/task/{task_id}",
headers=headers
)
status = status_response.json()['status']
if status == 'completed':
download_response = requests.get(
f"{BASE_URL}/task/{task_id}/download",
headers=headers,
stream=True
)
save_path = output_path or video_path.replace('.mp4', '_clean.mp4')
with open(save_path, 'wb') as f:
for chunk in download_response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"视频处理完成,已保存到: {save_path}")
break
elif status == 'failed':
print(f"处理失败: {status_response.json()['error']}")
break
else:
print(f"处理中... 状态: {status}")
time.sleep(10) # 视频处理等待更长
# 使用示例
remove_watermark_from_video("watermarked_video.mp4")
JavaScript 脚本集成
Node.js 图片去水印
const fs = require('fs');
const http = require('http');
const https = require('https');
const FormData = require('form-data');
const API_KEY = 'your_api_key_here';
const BASE_URL = 'https://sora2watermarkremover.net/api/v1';
async function removeWatermark(imagePath) {
const formData = new FormData();
formData.append('file', fs.createReadStream(imagePath));
formData.append('mode', 'auto');
// 上传图片
const uploadResponse = await new Promise((resolve, reject) => {
formData.submit({
url: `${BASE_URL}/image/remove-watermark`,
headers: { 'Authorization': `Bearer ${API_KEY}` },
protocol: 'https:'
}, (err, res) => {
if (err) return reject(err);
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
});
});
const taskId = uploadResponse.task_id;
console.log(`任务已提交: ${taskId}`);
// 轮询状态
let status = 'processing';
while (status !== 'completed' && status !== 'failed') {
const statusRes = await new Promise((resolve, reject) => {
https.get(`${BASE_URL}/task/${taskId}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', reject);
});
status = statusRes.status;
console.log(`状态: ${status}`);
if (status !== 'completed' && status !== 'failed') {
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
if (status === 'completed') {
// 下载结果
const outputPath = imagePath.replace('.jpg', '_clean.jpg');
const file = fs.createWriteStream(outputPath);
https.get(`${BASE_URL}/task/${taskId}/download`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}, (res) => {
res.pipe(file);
file.on('finish', () => {
file.close();
console.log(`处理完成,已保存到: ${outputPath}`);
});
});
}
}
// 使用示例
removeWatermark('watermarked_photo.jpg');
前端 JavaScript(浏览器端)
async function removeWatermarkBrowser(file, apiKey) {
const formData = new FormData();
formData.append('file', file);
formData.append('mode', 'auto');
// 上传图片
const uploadRes = await fetch('https://sora2watermarkremover.net/api/v1/image/remove-watermark', {
method: 'POST',
headers: { 'Authorization': `Bearer ${apiKey}` },
body: formData
});
const task = await uploadRes.json();
console.log(`任务已提交: ${task.task_id}`);
// 轮询状态
let status = 'processing';
while (status !== 'completed' && status !== 'failed') {
const statusRes = await fetch(
`https://sora2watermarkremover.net/api/v1/task/${task.task_id}`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
const statusData = await statusRes.json();
status = statusData.status;
console.log(`状态: ${status}`);
if (status !== 'completed' && status !== 'failed') {
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
if (status === 'completed') {
// 下载结果
const downloadRes = await fetch(
`https://sora2watermarkremover.net/api/v1/task/${task.task_id}/download`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
const blob = await downloadRes.blob();
// 创建下载链接
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'clean_image.jpg';
a.click();
URL.revokeObjectURL(url);
}
}
批量处理方案
并发控制
处理大量文件时,建议限制并发请求数量以避免触发速率限制:
import concurrent.futures
import os
def batch_with_concurrency(input_dir, output_dir, max_workers=5):
"""带并发控制的批量处理"""
os.makedirs(output_dir, exist_ok=True)
images = [
f for f in os.listdir(input_dir)
if f.lower().endswith(('.jpg', '.jpeg', '.png'))
]
def process_one(image):
input_path = os.path.join(input_dir, image)
output_path = os.path.join(output_dir, f"clean_{image}")
remove_watermark_from_image(input_path, output_path)
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(process_one, img) for img in images]
for i, future in enumerate(concurrent.futures.as_completed(futures)):
print(f"[{i+1}/{len(images)}] 完成")
try:
future.result()
except Exception as e:
print(f"错误: {e}")
print("全部处理完成")
错误处理与重试
import time
def remove_watermark_with_retry(image_path, max_retries=3):
"""带重试机制的去水印函数"""
for attempt in range(max_retries):
try:
remove_watermark_from_image(image_path)
return True
except Exception as e:
print(f"第 {attempt + 1} 次尝试失败: {e}")
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 5 # 指数退避
print(f"等待 {wait_time} 秒后重试...")
time.sleep(wait_time)
else:
print(f"所有重试失败,跳过文件")
return False
API 使用最佳实践
密钥安全
- 不要将 API Key 硬编码在代码中
- 使用环境变量存储:
export API_KEY="your_key" - 在 Python 中使用
os.environ.get('API_KEY')读取 - 不要将 Key 提交到 GitHub 等公共仓库
文件预处理
- 上传前确认文件大小不超过 200MB
- 确认文件格式为支持的类型(JPEG/PNG 图片,MP4/MOV 视频)
- 大文件建议先压缩以节省上传时间和流量
额度管理
- 定期查询账户余额,避免额度耗尽导致任务失败
- 批量处理前估算所需额度
- 设置监控告警,额度不足时及时充值
常见问题 FAQ
Q:API 有速率限制吗?
有。建议单次并发不超过 10 个请求。如需更高并发,请联系技术支持申请提升限制。
Q:处理失败会扣费吗?
不会。只有处理成功的任务才会扣除额度。因网络、格式不支持等原因导致的失败不会扣费。
Q:支持哪些文件格式?
图片:JPEG、PNG 视频:MP4、MOV
Q:如何处理超过 200MB 的文件?
建议先使用 ffmpeg 等工具压缩视频文件,或使用 Photoshop 等工具压缩图片文件后再上传。
Q:API 支持回调通知吗?
目前支持轮询方式获取处理状态。回调通知功能正在开发中,敬请期待。
总结
sora2watermarkremover.net 的 API 接口为开发者提供了灵活、高效的水印去除能力。通过简单的 HTTP 请求即可集成到任何技术栈中,支持 Python、JavaScript、Node.js 等主流语言。
对于批量处理场景,使用并发控制和重试机制可以大幅提升处理效率。新用户有 10 条免费额度,可以免费测试 API 接口的效果和功能。
- 图片去水印:$0.04/张起
- 视频去水印:$0.5/视频起
- 支持 1080p 输出,最大 200MB
如需技术支持或批量定制方案,请通过 sora2watermarkremover.net 联系官方团队。
免责声明:本文内容仅供参考。使用去水印 API 时,请确保你拥有图片或视频的使用权或授权。去除他人版权水印可能违反 DMCA(数字千年版权法)和相关版权法规。如果你是内容的原创作者,通过 API 去除自己内容上的水印用于个人或商业项目是合理的。建议在商业使用前咨询法律顾问。
