convert_to_grayscale
Convert images to grayscale by transforming them into a monochrome format. Use this tool for enhancing visual simplicity or preparing images for specific processing workflows.
Instructions
将图片转换为灰度图
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| image_source | Yes | 图片源,可以是文件路径或base64编码的图片数据 |
Implementation Reference
- tools/color_adjust.py:455-504 (handler)Core handler function implementing the grayscale conversion logic using PIL: loads image, calls image.convert('L'), processes and returns output as JSON via TextContent.async def convert_to_grayscale(image_source: str) -> list[TextContent]: """ 将图片转换为灰度图 Args: image_source: 图片数据(base64编码)或文件路径 Returns: 灰度图片数据 """ try: # 验证参数 if not image_source: raise ValidationError("图片数据不能为空") # 加载图片 image = processor.load_image(image_source) # 转换为灰度图 grayscale_image = image.convert('L') # 输出处理后的图片 output_info = processor.output_image(grayscale_image, "grayscale") result = { "success": True, "message": "图片转换为灰度图成功", "data": { **output_info, "original_mode": image.mode, "new_mode": grayscale_image.mode, "size": image.size } } 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:444-457 (registration)MCP tool registration decorator @mcp.tool() with input schema via Annotated[str, Field(...)], wrapper that delegates to the core handler color_convert_to_grayscale.@mcp.tool() def convert_to_grayscale( image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")] ) -> str: """将图片转换为灰度图""" try: result = safe_run_async(color_convert_to_grayscale(image_source)) return result[0].text except Exception as e: return json.dumps({ "success": False, "error": f"转换为灰度图失败: {str(e)}" }, ensure_ascii=False, indent=2)
- tools/color_adjust.py:105-118 (schema)JSON schema definition for the convert_to_grayscale tool input, part of get_color_adjust_tools() tool list (may be auxiliary).Tool( name="convert_to_grayscale", description="将图片转换为灰度图", inputSchema={ "type": "object", "properties": { "image_source": { "type": "string", "description": "图片数据(base64编码)或文件路径" } }, "required": ["image_source"] } ),