62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
from enum import Enum
|
|
from typing import Optional, List
|
|
from urllib.parse import urlparse, urlencode
|
|
|
|
class ImageFormat(Enum):
|
|
ORIGINAL = "original"
|
|
WEBP = "webp"
|
|
HEIC = "heic"
|
|
TPG = "tpg"
|
|
AVIF = "avif"
|
|
|
|
class ImageProcessor:
|
|
def __init__(self, url: Optional[str]):
|
|
self.url = url
|
|
self.params = []
|
|
|
|
def thumbnail(self, width: int, height: int) -> 'ImageProcessor':
|
|
"""缩略图,按比例缩放"""
|
|
self.params.append(f"thumbnail/{width}x{height}")
|
|
return self
|
|
|
|
def crop(self, width: int, height: int) -> 'ImageProcessor':
|
|
"""居中裁剪"""
|
|
self.params.append(f"crop/{width}x{height}")
|
|
return self
|
|
|
|
def quality(self, value: int) -> 'ImageProcessor':
|
|
"""设置图片质量 1-100"""
|
|
self.params.append(f"quality/{max(1, min(100, value))}")
|
|
return self
|
|
|
|
def format(self, fmt: ImageFormat) -> 'ImageProcessor':
|
|
"""转换图片格式"""
|
|
if fmt != ImageFormat.ORIGINAL:
|
|
self.params.append(f"format/{fmt.value}")
|
|
return self
|
|
|
|
def blur(self, radius: int = 10) -> 'ImageProcessor':
|
|
"""高斯模糊"""
|
|
self.params.append(f"blur/radius/{radius}")
|
|
return self
|
|
|
|
def watermark(self, text: str) -> 'ImageProcessor':
|
|
"""文字水印"""
|
|
self.params.append(f"watermark/2/text/{text}")
|
|
return self
|
|
|
|
def build(self) -> Optional[str]:
|
|
"""生成最终的图片 URL"""
|
|
if not self.url:
|
|
return None
|
|
|
|
if not self.params:
|
|
return self.url
|
|
|
|
# 拼接处理参数
|
|
rules = "/".join(self.params)
|
|
return f"{self.url}?imageMogr2/{rules}"
|
|
|
|
def process_image(url: Optional[str]) -> ImageProcessor:
|
|
"""创建图片处理器"""
|
|
return ImageProcessor(url) |