mcpField
I
image-generation

image-generation

github.com/answerzhao创意与媒体2645 次安装41 周前更新
代码仓库

关于 image-generation

面向开发者的文本生成图像技能,介绍如何通过 z-ai-web-dev-sdk 或 z-ai CLI 实现图像生成,涵盖后端调用、尺寸选择和批量处理。

主要功能

  1. 01使用 z-ai-web-dev-sdk 后端生成图像
  2. 02通过 CLI 生成图像
  3. 03选择支持的图像尺寸
  4. 04批量生成实现示例
  5. 05提示词与错误处理建议

适用场景

  1. 01制作网站横幅和视觉素材
  2. 02生成产品图像与模型图
  3. 03制作博客插图和缩略图

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/answerzhao/agent-skills --skill image-generation

安装后在 Claude Code 中输入/image-generation确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.DS_Store
LICENSE.txt
scripts/
.DS_Store
image-generation.ts

详细介绍

图像生成技能

本技能指导如何使用 z-ai-web-dev-sdk 包和 CLI 工具实现图像生成功能,从而能够根据文本描述创建高质量图像。

技能路径

技能位置:{project_path}/skills/image-generation

本技能位于你项目中的上述路径。

参考脚本:{Skill Location}/scripts/ 目录中提供了示例测试脚本,可用于快速测试和参考。查看 {Skill Location}/scripts/image-generation.ts 获取一个可运行的示例。

概述

图像生成允许你构建使用 AI 模型根据文本提示词创建视觉内容的应用,从而支持创意工作流、设计自动化和视觉内容生产。

重要:z-ai-web-dev-sdk 必须仅在 后端代码中使用。切勿在客户端代码中使用它。

先决条件

z-ai-web-dev-sdk 包已安装。按下文示例所示导入它。

基本图像生成

简单图像创建
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateImage(prompt, outputPath) {
  const zai = await ZAI.create();

  const response = await zai.images.generations.create({
    prompt: prompt,
    size: '1024x1024'
  });

  const imageBase64 = response.data[0].base64;
  
  // Save image
  const buffer = Buffer.from(imageBase64, 'base64');
  fs.writeFileSync(outputPath, buffer);
  
  console.log(`Image saved to ${outputPath}`);
  return outputPath;
}

// Usage
await generateImage(
  'A cute cat playing in the garden',
  './cat_image.png'
);
多种图像尺寸
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

// Supported sizes
const SUPPORTED_SIZES = [
  '1024x1024',  // Square
  '768x1344',   // Portrait
  '864x1152',   // Portrait
  '1344x768',   // Landscape
  '1152x864',   // Landscape
  '1440x720',   // Wide landscape
  '720x1440'    // Tall portrait
];

async function generateImageWithSize(prompt, size, outputPath) {
  if (!SUPPORTED_SIZES.includes(size)) {
    throw new Error(`Unsupported size: ${size}. Use one of: ${SUPPORTED_SIZES.join(', ')}`);
  }

  const zai = await ZAI.create();

  const response = await zai.images.generations.create({
    prompt: prompt,
    size: size
  });

  const imageBase64 = response.data[0].base64;
  const buffer = Buffer.from(imageBase64, 'base64');
  fs.writeFileSync(outputPath, buffer);

  return {
    path: outputPath,
    size: size,
    fileSize: buffer.length
  };
}

// Usage - Different sizes
await generateImageWithSize(
  'A beautiful landscape',
  '1344x768',
  './landscape.png'
);

await generateImageWithSize(
  'A portrait of a person',
  '768x1344',
  './portrait.png'
);

CLI 工具用法

z-ai CLI 工具提供了一种直接从命令行生成图像的便捷方式。

基本 CLI 用法
# Generate image with full options
z-ai image --prompt "A beautiful landscape" --output "./image.png"

# Short form
z-ai image -p "A cute cat" -o "./cat.png"

# Specify size
z-ai image -p "A sunset" -o "./sunset.png" -s 1344x768

# Portrait orientation
z-ai image -p "A portrait" -o "./portrait.png" -s 768x1344
CLI 用例
# Website hero image
z-ai image -p "Modern tech office with diverse team collaborating" -o "./hero.png" -s 1440x720

# Product image
z-ai image -p "Sleek smartphone on minimalist desk, professional product photography" -o "./product.png" -s 1024x1024

# Blog post illustration
z-ai image -p "Abstract visualization of data flowing through networks" -o "./blog_header.png" -s 1344x768

# Social media content
z-ai image -p "Vibrant illustration of community connection" -o "./social.png" -s 1024x1024

# Website favicon/logo
z-ai image -p "Simple geometric logo with blue gradient, minimal design" -o "./logo.png" -s 1024x1024

# Background pattern
z-ai image -p "Subtle geometric pattern, pastel colors, website background" -o "./bg_pattern.png" -s 1440x720

高级用例

批量图像生成
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';

async function generateImageBatch(prompts, outputDir, size = '1024x1024') {
  const zai = await ZAI.create();

  // Ensure output directory exists
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const results = [];

  for (let i = 0; i < prompts.length; i++) {
    try {
      const prompt = prompts[i];
      const filename = `image_${i + 1}.png`;
      const outputPath = path.join(outputDir, filename);

      const response = await zai.images.generations.create({
        prompt: prompt,
        size: size
      });

      const imageBase64 = response.data[0].base64;
      const buffer = Buffer.from(imageBase64, 'base64');
      fs.writeFileSync(outputPath, buffer);

      results.push({
        success: true,
        prompt: prompt,
        path: outputPath,
        size: buffer.length
      });

      console.log(`✓ Generated: ${filename}`);
    } catch (error) {
      results.push({
        success: false,
        prompt: prompts[i],
        error: error.message
      });

      console.error(`✗ Failed: ${prompts[i]} - ${error.message}`);
    }
  }

  return results;
}

// Usage
const prompts = [
  'A serene mountain landscape at sunset',
  'A futuristic city with flying cars',
  'An underwater coral reef teeming with life'
];

const results = await generateImageBatch(prompts, './generated-images');
console.log(`Generated ${results.filter(r => r.success).length} images`);
图像生成服务
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';

class ImageGenerationService {
  constructor(outputDir = './generated-images') {
    this.outputDir = outputDir;
    this.zai = null;
    this.cache = new Map();
  }

  async initialize() {
    this.zai = await ZAI.create();
    
    if (!fs.existsSync(this.outputDir)) {
      fs.mkdirSync(this.outputDir, { recursive: true });
    }
  }

  generateCacheKey(prompt, size) {
    return crypto
      .createHash('md5')
      .update(`${prompt}-${size}`)
      .digest('hex');
  }

  async generate(prompt, options = {}) {
    const {
      size = '1024x1024',
      useCache = true,
      filename = null
    } = options;

    // Check cache
    const cacheKey = this.generateCacheKey(prompt, size);
    
    if (useCache && this.cache.has(cacheKey)) {
      const cachedPath = this.cache.get(cacheKey);
      if (fs.existsSync(cachedPath)) {
        return {
          path: cachedPath,
          cached: true,
          prompt: prompt,
          size: size
        };
      }
    }

    // Generate new image
    const response = await this.zai.images.generations.create({
      prompt: prompt,
      size: size
    });

    const imageBase64 = response.data[0].base64;
    const buffer = Buffer.from(imageBase64, 'base64');

    // Determine output path
    const outputFilename = filename || `${cacheKey}.png`;
    const outputPath = path.join(this.outputDir, outputFilename);

    fs.writeFileSync(outputPath, buffer);

    // Cache result
    if (useCache) {
      this.cache.set(cacheKey, outputPath);
    }

    return {
      path: outputPath,
      cached: false,
      prompt: prompt,
      size: size,
      fileSize: buffer.length
    };
  }

  clearCache() {
    this.cache.clear();
  }

  getCacheSize() {
    return this.cache.size;
  }
}

// Usage
const service = new ImageGenerationService();
await service.initialize();

const result = await service.generate(
  'A modern office space',
  { size: '1440x720' }
);

console.log('Generated:', result.path);
网站资源生成器
# Using CLI for quick website asset generation
z-ai image -p "Modern tech hero banner, blue gradient" -o "./assets/hero.png" -s 1440x720
z-ai image -p "Team collaboration illustration" -o "./assets/team.png" -s 1344x768
z-ai image -p "Simple geometric logo" -o "./assets/logo.png" -s 1024x1024

最佳实践

1. 有效的提示词工程
function buildEffectivePrompt(subject, style, details = []) {
  const components = [
    subject,
    style,
    ...details,
    'high quality',
    'detailed'
  ];

  return components.filter(Boolean).join(', ');
}

// Usage
const prompt = buildEffectivePrompt(
  'mountain landscape',
  'oil painting style',
  ['sunset lighting', 'dramatic clouds', 'reflection in lake']
);

// Result: "mountain landscape, oil painting style, sunset lighting, dramatic clouds, reflection in lake, high quality, detailed"
2. 尺寸选择辅助工具
function selectOptimalSize(purpose) {
  const sizeMap = {
    'hero-banner': '1440x720',
    'blog-header': '1344x768',
    'social-square': '1024x1024',
    'portrait': '768x1344',
    'product': '1024x1024',
    'landscape': '1344x768',
    'mobile-banner': '720x1440',
    'thumbnail': '1024x1024'
  };

  return sizeMap[purpose] || '1024x1024';
}

// Usage
const size = selectOptimalSize('hero-banner');
await generateImage('website hero image', size, './hero.png');
3. 错误处理
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function safeGenerateImage(prompt, size, outputPath, retries = 3) {
  let lastError;

  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      const zai = await ZAI.create();

      const response = await zai.images.generations.create({
        prompt: prompt,
        size: size
      });

      if (!response.data || !response.data[0] || !response.data[0].base64) {
        throw new Error('Invalid response from image generation API');
      }

      const imageBase64 = response.data[0].base64;
      const buffer = Buffer.from(imageBase64, 'base64');
      fs.writeFileSync(outputPath, buffer);

      return {
        success: true,
        path: outputPath,
        attempts: attempt
      };
    } catch (error) {
      lastError = error;
      console.error(`Attempt ${attempt} failed:`, error.message);

      if (attempt < retries) {
        // Wait before retry (exponential backoff)
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
      }
    }
  }

  return {
    success: false,
    error: lastError.message,
    attempts: retries
  };
}

常见用例

  1. 网站设计:生成主视觉图、背景和视觉资源
  2. 营销材料:创建社交媒体图形和宣传图片
  3. 产品可视化:生成产品模型和变体
  4. 内容创作:制作博客文章插图和缩略图
  5. 品牌资源:创建 logo、图标和品牌图像
  6. UI/UX 设计:生成界面元素和插图
  7. 游戏开发:创建概念艺术和游戏资源
  8. 电子商务:生成产品图片和生活方式场景图

集成示例

Express.js API 端点
import express from 'express';
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';

const app = express();
app.use(express.json());
app.use('/images', express.static('generated-images'));

let zaiInstance;
const outputDir = './generated-images';

async function initZAI() {
  zaiInstance = await ZAI.create();
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
}

app.post('/api/generate-image', async (req, res) => {
  try {
    const { prompt, size = '1024x1024' } = req.body;

    if (!prompt) {
      return res.status(400).json({ error: 'Prompt is required' });
    }

    const response = await zaiInstance.images.generations.create({
      prompt: prompt,
      size: size
    });

    const imageBase64 = response.data[0].base64;
    const buffer = Buffer.from(imageBase64, 'base64');
    
    const filename = `img_${Date.now()}.png`;
    const filepath = path.join(outputDir, filename);
    fs.writeFileSync(filepath, buffer);

    res.json({
      success: true,
      imageUrl: `/images/${filename}`,
      prompt: prompt,
      size: size
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

initZAI().then(() => {
  app.listen(3000, () => {
    console.log('Image generation API running on port 3000');
  });
});

脚本中的 CLI 集成

Shell 脚本示例
#!/bin/bash

# Generate website assets using CLI
echo "Generating website assets..."

z-ai image -p "Modern tech hero banner, blue gradient" -o "./assets/hero.png" -s 1440x720
z-ai image -p "Team collaboration illustration" -o "./assets/team.png" -s 1344x768
z-ai image -p "Simple geometric logo" -o "./assets/logo.png" -s 1024x1024

echo "Assets generated successfully!"

故障排除

问题:"SDK must be used in backend"

  • 解决方案:确保 z-ai-web-dev-sdk 仅在服务器端代码中使用

问题:无效的尺寸参数

  • 解决方案:仅使用支持的尺寸:1024x1024、768x1344、864x1152、1344x768、1152x864、1440x720、720x1440

问题:生成的图像与提示词不匹配

  • 解决方案:让提示词更具体、更具描述性。包含风格、细节和质量术语

问题:未找到 CLI 命令

  • 解决方案:确保 z-ai CLI 已正确安装并位于 PATH 中

问题:图像文件已损坏

  • 解决方案:验证 base64 解码和文件写入是否正确

提示词工程技巧

好的提示词
  • ✓ "Professional product photography of wireless headphones, white background, studio lighting, high quality"
  • ✓ "Mountain landscape at golden hour, oil painting style, dramatic clouds, detailed"
  • ✓ "Modern minimalist logo for tech company, blue and white, geometric shapes"
差的提示词
  • ✗ "headphones"
  • ✗ "picture of mountains"
  • ✗ "logo"
提示词组成部分
  1. 主体:你想要看到的内容
  2. 风格:艺术风格、摄影风格等
  3. 细节:具体元素、颜色、氛围
  4. 质量:"high quality"、"detailed"、"professional"

支持的图像尺寸

  • 1024x1024 - 正方形
  • 768x1344 - 竖版
  • 864x1152 - 竖版
  • 1344x768 - 横版
  • 1152x864 - 横版
  • 1440x720 - 宽横版
  • 720x1440 - 高竖版

请记住

  • 仅在后端代码中使用 z-ai-web-dev-sdk
  • SDK 已安装 - 按所示方式导入
  • CLI 工具可用于快速生成图像
  • 支持的尺寸是特定的 - 请使用提供的列表
  • Base64 图像在保存前需要解码
  • 考虑对重复的提示词进行缓存
  • 为生产应用程序实现重试逻辑
  • 使用描述性的提示词以获得更好的结果

评论

支持 Markdown