Files
2026-07-27 14:23:56 +08:00

37 lines
876 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""图片下载工具。
把图片 URL 下载成字节流,供 OCR(app.tool.ocr)与二维码识别
app.tool.cv / app.tool.qr_decode)直接消费,不落盘。
"""
from __future__ import annotations
import httpx
from app.core.logger import log
# 请求超时(秒)
_TIMEOUT = 20
def download_image(url: str) -> bytes | None:
"""下载图片。
Args:
url: 图片地址。
Returns:
图片字节流;下载失败时返回 None。
"""
if not url or not url.startswith("http"):
return None
try:
with httpx.Client(timeout=_TIMEOUT, follow_redirects=True) as client:
response = client.get(url)
response.raise_for_status()
return response.content or None
except httpx.HTTPError as exc:
log.warning(f"图片下载失败: {url} | {exc}")
return None