Skip to main content
Glama

batch_convert_images

Convert multiple image files between formats like JPG, PNG, WebP, and AVIF in batch. Adjust quality, resize dimensions, and maintain aspect ratio for efficient image processing.

Instructions

批量转换多个图片文件

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
input_pathsNo源图片文件路径数组(与input_files二选一)
input_filesNo上传的文件数据数组(与input_paths二选一)
output_formatYes目标格式
qualityNo压缩质量
widthNo目标宽度
heightNo目标高度
maintain_aspect_ratioNo保持宽高比
output_directoryNo输出目录

Implementation Reference

  • The core handler function for batch converting images. It processes either file paths or input file data (buffers/base64), calls single convertImage for each, and returns array of results with success/error info.
    async batchConvertImages(options: BatchConvertOptions): Promise<BatchConvertResult[]> {
      const { input_paths, input_files, output_format, quality, width, height, maintain_aspect_ratio, output_directory } = options;
      const results: BatchConvertResult[] = [];
    
      // 处理文件路径方式
      if (input_paths && input_paths.length > 0) {
        for (const inputPath of input_paths) {
          try {
            const outputPath = output_directory 
              ? path.join(output_directory, this.generateOutputFilename(inputPath, output_format))
              : this.generateOutputPath(inputPath, output_format);
    
            await this.convertImage({
              input_path: inputPath,
              output_format,
              quality,
              width,
              height,
              maintain_aspect_ratio,
              output_path: outputPath
            });
    
            results.push({
              success: true,
              output_path: outputPath
            });
          } catch (error) {
            results.push({
              success: false,
              error: error instanceof Error ? error.message : String(error)
            });
          }
        }
      }
    
      // 处理上传文件方式
      if (input_files && input_files.length > 0) {
        for (const inputFile of input_files) {
          try {
            const outputPath = output_directory 
              ? path.join(output_directory, this.generateOutputFilename(inputFile.filename, output_format))
              : this.generateOutputPath(inputFile.filename, output_format);
    
            await this.convertImage({
              input_data: inputFile.data,
              input_filename: inputFile.filename,
              output_format,
              quality,
              width,
              height,
              maintain_aspect_ratio,
              output_path: outputPath
            });
    
            results.push({
              success: true,
              output_path: outputPath
            });
          } catch (error) {
            results.push({
              success: false,
              error: error instanceof Error ? error.message : String(error)
            });
          }
        }
      }
    
      return results;
    }
  • TypeScript interfaces defining the input (BatchConvertOptions) and output (BatchConvertResult) types for the batch_convert_images tool.
    export interface BatchConvertOptions {
      input_paths?: string[];
      input_files?: Array<{
        data: Buffer | string;
        filename: string;
      }>; // 支持上传的文件数据
      output_format: string;
      quality?: number;
      width?: number;
      height?: number;
      maintain_aspect_ratio?: boolean;
      output_directory?: string;
    }
    
    export interface ConvertResult {
      output_path: string;
      file_size: number;
      dimensions: {
        width: number;
        height: number;
      };
      format: string;
    }
    
    export interface BatchConvertResult {
      success: boolean;
      output_path?: string;
      error?: string;
    }
  • src/index.ts:111-172 (registration)
    Tool registration in the MCP server's listTools handler, defining the name, description, and JSON input schema.
    {
      name: 'batch_convert_images',
      description: '批量转换多个图片文件',
      inputSchema: {
        type: 'object',
        properties: {
          input_paths: {
            type: 'array',
            items: { type: 'string' },
            description: '源图片文件路径数组(与input_files二选一)'
          },
          input_files: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                data: {
                  type: 'string',
                  description: '文件数据(Buffer或base64字符串)'
                },
                filename: {
                  type: 'string',
                  description: '文件名'
                }
              },
              required: ['data', 'filename']
            },
            description: '上传的文件数据数组(与input_paths二选一)'
          },
          output_format: {
            type: 'string',
            description: '目标格式'
          },
          quality: {
            type: 'number',
            minimum: 1,
            maximum: 100,
            description: '压缩质量'
          },
          width: {
            type: 'number',
            minimum: 1,
            description: '目标宽度'
          },
          height: {
            type: 'number',
            minimum: 1,
            description: '目标高度'
          },
          maintain_aspect_ratio: {
            type: 'boolean',
            default: true,
            description: '保持宽高比'
          },
          output_directory: {
            type: 'string',
            description: '输出目录'
          }
        },
        required: ['output_format']
      }
    },
  • Zod schema for validating batch_convert_images input arguments before calling the handler.
    const BatchConvertArgsSchema = z.object({
      input_paths: z.array(z.string()).optional().describe('源图片文件路径数组'),
      input_files: z.array(z.object({
        data: z.string().describe('文件数据(Buffer或base64字符串)'),
        filename: z.string().describe('文件名')
      })).optional().describe('上传的文件数据数组'),
      output_format: z.string().describe('目标格式'),
      quality: z.number().min(1).max(100).optional().describe('压缩质量'),
      width: z.number().positive().optional().describe('目标宽度'),
      height: z.number().positive().optional().describe('目标高度'),
      maintain_aspect_ratio: z.boolean().default(true).describe('保持宽高比'),
      output_directory: z.string().optional().describe('输出目录(可选)')
    });
  • MCP tool call dispatcher case that validates args with Zod, invokes the converter handler, formats results into text response.
    case 'batch_convert_images': {
      const validatedArgs = BatchConvertArgsSchema.parse(args);
      const results = await this.converter.batchConvertImages(validatedArgs);
      const successCount = results.filter(r => r.success).length;
      const failureCount = results.length - successCount;
      
      let resultText = `批量转换完成!\n成功:${successCount} 个文件\n失败:${failureCount} 个文件\n\n`;
      
      // 确定输入源的总数
      const totalInputs = (validatedArgs.input_paths?.length || 0) + (validatedArgs.input_files?.length || 0);
      
      results.forEach((result, index) => {
        let inputName = `文件${index + 1}`;
        
        // 优先从input_paths获取名称
        if (validatedArgs.input_paths && index < validatedArgs.input_paths.length) {
          inputName = validatedArgs.input_paths[index];
        } 
        // 然后从input_files获取名称
        else if (validatedArgs.input_files) {
          const fileIndex = index - (validatedArgs.input_paths?.length || 0);
          if (fileIndex >= 0 && fileIndex < validatedArgs.input_files.length) {
            inputName = validatedArgs.input_files[fileIndex].filename;
          }
        }
        
        if (result.success) {
          resultText += `✓ ${inputName} -> ${result.output_path}\n`;
        } else {
          resultText += `✗ ${inputName}: ${result.error}\n`;
        }
      });
    
      return {
        content: [
          {
            type: 'text',
            text: resultText
          }
        ]
      };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It states 'convert' which implies mutation but doesn't disclose whether files are overwritten, if conversion is lossy, authentication requirements, rate limits, or error handling for partial failures in batch operations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient phrase that directly states the tool's purpose without redundancy. It's appropriately sized for a batch processing tool and front-loads the core functionality.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a batch mutation tool with 8 parameters, no annotations, and no output schema, the description is insufficient. It lacks critical context about output location, file naming conventions, conversion behavior, error handling, and performance characteristics that would help an agent use it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, providing detailed parameter documentation. The description adds no parameter-specific information beyond the schema's comprehensive descriptions, so it meets the baseline for high schema coverage without compensating value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description '批量转换多个图片文件' clearly states the action (convert) and resource (multiple image files) in Chinese. It distinguishes from sibling 'convert_image' by specifying batch processing, but doesn't explicitly contrast with other siblings like 'get_image_info' or 'list_supported_formats'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention when batch conversion is preferred over single-file 'convert_image', nor does it reference prerequisites like supported formats or file size limits.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/pickstar-2002/image-mcp'

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