调用 API 前必须先获取 API Key
所有 API 请求均需通过 X-API-Key 请求头进行身份认证。没有有效的 API Key,任何端点都无法调用。
环境要求
- Python 3.8+
- requests 库
- Pillow 库(用于获取图片尺寸)
安装依赖
pip install requests Pillow
完整示例代码
import os
import requests
from PIL import Image
API_KEY = os.environ.get("IMGROUTE_API_KEY", "sk-ir-your-key-here")
BASE_URL = "https://imgroute.com/api/v1"
def get_image_info(file_path):
with Image.open(file_path) as im:
width, height = im.size
file_size = os.path.getsize(file_path)
mime_type = f"image/{os.path.splitext(file_path)[1][1:]}"
return {"width": width, "height": height, "size": file_size, "mime_type": mime_type}
def upload_image(file_path, album_id=None):
info = get_image_info(file_path)
file_name = os.path.basename(file_path)
headers = {"X-API-Key": API_KEY}
payload = {
"file_name": file_name,
"file_size": info["size"],
"mime_type": info["mime_type"],
"width": info["width"],
"height": info["height"]
}
if album_id:
payload["album_id"] = album_id
response = requests.post(f"{BASE_URL}/upload", headers=headers, json=payload).json()
if not response.get("success"):
raise RuntimeError(f"预签名失败: {response.get('error')}")
upload_url = response["data"]["upload_url"]
cdn_url = response["data"]["cdn_url"]
with open(file_path, "rb") as f:
upload_response = requests.post(
upload_url,
files={"file": (file_name, f, info["mime_type"])}
).json()
if not upload_response.get("success"):
raise RuntimeError(f"上传失败: {upload_response.get('error')}")
return cdn_url
if __name__ == "__main__":
os.environ["IMGROUTE_API_KEY"] = "sk-ir-your-key-here"
try:
cdn_url = upload_image("./cat.jpg")
print(f"上传成功: {cdn_url}")
except Exception as e:
print(f"上传失败: {e}")
批量上传示例
import os
from pathlib import Path
def batch_upload(directory, extensions=["jpg", "png", "jpeg"]):
results = []
for ext in extensions:
for file_path in Path(directory).glob(f"*.{ext}"):
try:
cdn_url = upload_image(str(file_path))
results.append({"file": str(file_path), "url": cdn_url, "status": "success"})
except Exception as e:
results.append({"file": str(file_path), "error": str(e), "status": "failed"})
return results
if __name__ == "__main__":
results = batch_upload("./images")
for r in results:
status = r["status"]
file_name = os.path.basename(r["file"])
if status == "success":
print(f"[OK] {file_name}: {r['url']}")
else:
print(f"[FAIL] {file_name}: {r['error']}")
常见问题
Q: 如何获取图片尺寸?
使用 Pillow 库(如示例所示),或使用 image-size 库:
import sizeOf
dimensions = sizeOf("image.jpg")
width = dimensions["width"]
height = dimensions["height"]
Q: 如何处理上传失败?
使用重试机制:
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def upload_with_retry(file_path):
return upload_image(file_path)