mcpField
I
image-generation

image-generation

github.com/answerzhaoクリエイティブ・メディア2645 回インストール41 週間前に更新
リポジトリ

image-generation について

z-ai-web-dev-sdkまたはz-ai CLIでテキストから画像を生成する機能を実装する開発者向けスキルです。バックエンドでの利用、サイズ選択、バッチ生成などを扱います。

主な機能

  1. 01z-ai-web-dev-sdkによるバックエンド生成
  2. 02CLIでの画像生成
  3. 03対応画像サイズの選択
  4. 04バッチ生成の実装例
  5. 05プロンプトとエラー処理の指針

活用シーン

  1. 01Webサイトのバナーや素材の作成
  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);
Web サイトアセットジェネレーター
# 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. Web サイトのデザイン: ヒーロー画像、背景、ビジュアルアセットを生成する
  2. マーケティング資料: ソーシャルメディア用のグラフィックや宣伝用画像を作成する
  3. 製品のビジュアル化: 製品のモックアップやバリエーションを生成する
  4. コンテンツ制作: ブログ記事のイラストやサムネイルを作成する
  5. ブランドアセット: ロゴ、アイコン、ブランドイメージを作成する
  6. UI/UX デザイン: インターフェース要素やイラストを生成する
  7. ゲーム開発: コンセプトアートやゲームアセットを作成する
  8. E コマース: 製品画像やライフスタイル写真を生成する

統合例

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 統合

シェルスクリプトの例
#!/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 はバックエンドで使用する必要があります」

  • 解決策: z-ai-web-dev-sdk がサーバー側のコードでのみ使用されていることを確認してください

問題: サイズパラメーターが無効です

  • 解決策: サポートされているサイズのみを使用してください: 1024x1024、768x1344、864x1152、1344x768、1152x864、1440x720、720x1440

問題: 生成された画像がプロンプトと一致しません

  • 解決策: プロンプトをより具体的かつ詳細にしてください。スタイル、細部、品質を表す語句を含めてください

問題: CLI コマンドが見つかりません

  • 解決策: z-ai CLI が正しくインストールされ、PATH に含まれていることを確認してください

問題: 画像ファイルが破損しています

  • 解決策: base64 のデコードとファイルへの書き込みが正しく行われていることを確認してください

プロンプトエンジニアリングのヒント

良いプロンプト
  • ✓ 「ワイヤレスヘッドホンのプロフェッショナルな製品写真、白い背景、スタジオ照明、高品質」
  • ✓ 「ゴールデンアワーの山岳風景、油絵風、ドラマチックな雲、細密な描写」
  • ✓ 「テクノロジー企業向けのモダンでミニマルなロゴ、青と白、幾何学的な形」
良くないプロンプト
  • ✗ 「ヘッドホン」
  • ✗ 「山の写真」
  • ✗ 「ロゴ」
プロンプトの構成要素
  1. 被写体: 見たいもの
  2. スタイル: アートスタイル、写真のスタイルなど
  3. 詳細: 具体的な要素、色、雰囲気
  4. 品質: 「高品質」、「細密な描写」、「プロフェッショナル」

サポートされている画像サイズ

  • 1024x1024 - 正方形
  • 768x1344 - 縦長
  • 864x1152 - 縦長
  • 1344x768 - 横長
  • 1152x864 - 横長
  • 1440x720 - ワイドな横長
  • 720x1440 - 縦長

覚えておくこと

  • z-ai-web-dev-sdk はバックエンドコードでのみ使用してください
  • SDK はすでにインストールされています。例のとおりにインポートしてください
  • 画像をすばやく生成するための CLI ツールを利用できます
  • 対応サイズは決まっています。指定されたリストを使用してください
  • Base64 形式の画像は、保存する前にデコードする必要があります
  • プロンプトを繰り返し使用する場合は、キャッシュを検討してください
  • 本番アプリケーションでは、リトライ処理を実装してください
  • より良い結果を得るために、具体的なプロンプトを使用してください

コメント