Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

resize_image

Resize images to specific dimensions while optionally maintaining aspect ratio and selecting resampling algorithms for quality control.

Instructions

调整图片大小

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据
widthYes目标宽度(像素)
heightYes目标高度(像素)
keep_aspect_ratioNo是否保持宽高比,True时会按比例缩放
resampleNo重采样算法:LANCZOS(高质量)、BILINEAR(平滑)、NEAREST(快速)LANCZOS

Implementation Reference

  • Core handler function that performs the image resizing using PIL, with aspect ratio handling, resampling, validation, and JSON output.
    async def resize_image(image_source: str, width: int, height: int, 
                          keep_aspect_ratio: bool = True, resample: str = "LANCZOS") -> list[TextContent]:
        """
        调整图片大小
        
        Args:
            image_source: 图片源(文件路径或base64编码数据)
            width: 目标宽度
            height: 目标高度
            keep_aspect_ratio: 是否保持宽高比
            resample: 重采样方法
            
        Returns:
            调整后的图片数据
        """
        try:
            # 验证参数
            if not image_source:
                raise ValidationError("图片源不能为空")
            
            ensure_valid_dimensions(width, height)
            
            # 验证重采样方法
            resample_methods = {
                'NEAREST': Image.NEAREST,
                'BILINEAR': Image.BILINEAR,
                'BICUBIC': Image.BICUBIC,
                'LANCZOS': Image.LANCZOS
            }
            
            if resample.upper() not in resample_methods:
                raise ValidationError(f"不支持的重采样方法: {resample}")
            
            # 加载图片
            image = processor.load_image(image_source)
            original_size = image.size
            
            # 计算目标尺寸
            if keep_aspect_ratio:
                # 保持宽高比,计算实际尺寸
                aspect_ratio = original_size[0] / original_size[1]
                target_aspect_ratio = width / height
                
                if aspect_ratio > target_aspect_ratio:
                    # 以宽度为准
                    new_width = width
                    new_height = int(width / aspect_ratio)
                else:
                    # 以高度为准
                    new_height = height
                    new_width = int(height * aspect_ratio)
            else:
                new_width, new_height = width, height
            
            # 调整大小
            resized_image = image.resize(
                (new_width, new_height), 
                resample_methods[resample.upper()]
            )
            
            # 输出调整后的图片
            output_info = processor.output_image(resized_image, f"resize_{new_width}x{new_height}")
            
            result = {
                "success": True,
                "message": f"图片大小调整成功: {original_size} -> {(new_width, new_height)}",
                "data": {
                    **output_info,
                    "original_size": original_size,
                    "new_size": (new_width, new_height),
                    "keep_aspect_ratio": keep_aspect_ratio,
                    "resample_method": resample
                }
            }
            
            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:170-186 (registration)
    MCP tool registration using @mcp.tool() decorator, defines input schema via Annotated fields, and delegates to the core transform_resize_image implementation.
    @mcp.tool()
    def resize_image(
        image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")],
        width: Annotated[int, Field(description="目标宽度(像素)", gt=0)],
        height: Annotated[int, Field(description="目标高度(像素)", gt=0)],
        keep_aspect_ratio: Annotated[bool, Field(description="是否保持宽高比,True时会按比例缩放", default=True)],
        resample: Annotated[str, Field(description="重采样算法:LANCZOS(高质量)、BILINEAR(平滑)、NEAREST(快速)", default="LANCZOS")]
    ) -> str:
        """调整图片大小"""
        try:
            result = safe_run_async(transform_resize_image(image_source, width, height, keep_aspect_ratio, resample))
            return result[0].text
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": f"调整图片大小失败: {str(e)}"
            }, ensure_ascii=False, indent=2)
  • Tool schema definition including input schema, properties, constraints, and defaults for resize_image.
    Tool(
        name="resize_image",
        description="调整图片大小",
        inputSchema={
            "type": "object",
            "properties": {
                "image_data": {
                    "type": "string",
                    "description": "图片数据(base64编码)"
                },
                "width": {
                    "type": "integer",
                    "description": "目标宽度",
                    "minimum": 1,
                    "maximum": 4096
                },
                "height": {
                    "type": "integer",
                    "description": "目标高度",
                    "minimum": 1,
                    "maximum": 4096
                },
                "keep_aspect_ratio": {
                    "type": "boolean",
                    "description": "是否保持宽高比",
                    "default": True
                },
                "resample": {
                    "type": "string",
                    "description": "重采样方法(NEAREST, BILINEAR, BICUBIC, LANCZOS)",
                    "default": "LANCZOS"
                }
            },
            "required": ["image_data", "width", "height"]
        }
    ),

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/duke0317/ps-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server