""" 图片缩放核心逻辑 - 供 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)}" }