File size: 1,561 Bytes
bdcdaf4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | """
图片缩放核心逻辑 - 供 mcp.py 和 api.py 共用
"""
import io
import base64
from PIL import Image
async def do_resize(file_base64: str, width: int, height: int, format: str) -> dict:
"""执行图片缩放操作。
Args:
file_base64: 图片的Base64编码
width: 目标宽度
height: 目标高度
format: 输出格式(PNG、JPEG、WEBP)
Returns:
包含缩放结果的字典
"""
try:
# 解码Base64
image_data = base64.b64decode(file_base64)
image = Image.open(io.BytesIO(image_data))
# 检查源图片尺寸
if image.width < width or image.height < height:
return {
"success": False,
"message": f"源图片尺寸 ({image.width}x{image.height}) 小于目标尺寸 ({width}x{height})"
}
# 缩放图片
resized = image.resize((width, height), Image.Resampling.LANCZOS)
# 输出
output = io.BytesIO()
save_format = format.upper() if format.upper() != "JPEG" else "JPEG"
resized.save(output, format=save_format, quality=95)
output.seek(0)
# 编码输出
output_base64 = base64.b64encode(output.read()).decode('utf-8')
return {
"success": True,
"output_base64": output_base64,
"message": f"图片已缩放至 {width}x{height}"
}
except Exception as e:
return {
"success": False,
"message": f"缩放失败: {str(e)}"
} |