save_image
Save images to a specified path with customizable format and quality settings. Accepts file paths or base64-encoded image data for flexible input options.
Instructions
保存图片到指定路径
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| format | No | 图片格式,支持 PNG、JPEG、WEBP、BMP、TIFF 等 | PNG |
| image_source | Yes | 图片源,可以是文件路径或base64编码的图片数据 | |
| output_path | Yes | 输出文件路径,包含文件名和扩展名(如 'output.png') | |
| quality | No | 图片质量,范围 1-100,仅对 JPEG 格式有效 |
Implementation Reference
- tools/basic.py:154-212 (handler)Primary handler function that implements the save_image tool logic: parameter validation, image loading, saving via ImageProcessor, file size calculation, and JSON response generation.async def save_image(image_data: str, output_path: str, format: str = "PNG", quality: int = 95) -> list[TextContent]: """ 保存图片到指定路径 Args: image_data: 图片数据(base64编码) output_path: 输出文件路径 format: 图片格式 quality: 图片质量 Returns: 保存结果响应 """ try: # 验证参数 if not image_data or not output_path: raise ValidationError("图片数据和输出路径不能为空") if not validate_image_format(format): raise ValidationError(f"不支持的图片格式: {format}") if not (1 <= quality <= 100): raise ValidationError("图片质量必须在1-100之间") # 加载图片 image = processor.load_image(image_data) # 保存图片 saved_path = processor.save_image(image, output_path, format, quality) # 获取文件信息 file_size = os.path.getsize(saved_path) result = { "success": True, "message": "图片保存成功", "data": { "output_path": saved_path, "format": format, "file_size": file_size, "quality": quality } } return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))] except ValidationError as e: error_result = { "success": False, "error": f"参数验证失败: {str(e)}" } return [TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False))] except Exception as e: error_result = { "success": False, "error": f"图片保存失败: {str(e)}" } return [TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False))]
- main.py:121-137 (registration)Registers the save_image tool with FastMCP server using @mcp.tool() decorator, defines input schema via Annotated fields, and provides a synchronous wrapper around the async basic handler.@mcp.tool() def save_image( image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")], output_path: Annotated[str, Field(description="输出文件路径,包含文件名和扩展名(如 'output.png')")], format: Annotated[str, Field(description="图片格式,支持 PNG、JPEG、WEBP、BMP、TIFF 等", default="PNG")], quality: Annotated[int, Field(description="图片质量,范围 1-100,仅对 JPEG 格式有效", ge=1, le=100, default=95)] ) -> str: """保存图片到指定路径""" try: result = safe_run_async(basic_save_image(image_source, output_path, format, quality)) return result[0].text except Exception as e: return json.dumps({ "success": False, "error": f"保存图片失败: {str(e)}" }, ensure_ascii=False, indent=2)
- main.py:123-126 (schema)Pydantic schema definition for save_image tool inputs using Annotated and Field for validation, descriptions, defaults, and constraints.image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")], output_path: Annotated[str, Field(description="输出文件路径,包含文件名和扩展名(如 'output.png')")], format: Annotated[str, Field(description="图片格式,支持 PNG、JPEG、WEBP、BMP、TIFF 等", default="PNG")], quality: Annotated[int, Field(description="图片质量,范围 1-100,仅对 JPEG 格式有效", ge=1, le=100, default=95)]
- utils/image_processor.py:65-97 (helper)Low-level helper method in ImageProcessor class that performs the actual PIL Image.save() operation, handling directory creation, JPEG transparency conversion, and format-specific saving.def save_image(self, image: Image.Image, output_path: str, format: str = 'PNG', quality: int = 95) -> str: """ 保存图片到指定路径 Args: image: PIL Image对象 output_path: 输出文件路径 format: 图片格式 quality: 图片质量 (1-100) Returns: 保存的文件路径 """ try: # 确保输出目录存在 os.makedirs(os.path.dirname(output_path), exist_ok=True) # 保存图片 if format.upper() == 'JPEG': # JPEG不支持透明度,需要转换 if image.mode in ('RGBA', 'LA'): background = Image.new('RGB', image.size, (255, 255, 255)) background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None) image = background image.save(output_path, format=format, quality=quality) else: image.save(output_path, format=format) return output_path except Exception as e: raise IOError(f"图片保存失败: {str(e)}")