実践例

様々な使用例の実用的なサンプルとコードスニペット

実践例

Qwen Image Editの実用的な使用例を通じて、様々なシナリオでの活用方法を学びましょう。

🎯 基本的なテキスト編集

テキストの修正

// 商品価格の更新
const result = await editor.editText({
  image: './product-banner.jpg',
  prompt: '価格を「¥2,980」から「¥1,980」に変更してください'
});

// 日付の更新
const result = await editor.editText({
  image: './event-poster.jpg',
  prompt: '開催日を「2024年3月15日」から「2024年4月20日」に変更してください'
});

// 連絡先情報の更新
const result = await editor.editText({
  image: './business-card.jpg',
  prompt: '電話番号を「03-1234-5678」から「03-9876-5432」に変更してください'
});

テキストの翻訳

// 英語から日本語への翻訳
const result = await editor.editText({
  image: './english-menu.jpg',
  prompt: 'すべての英語テキストを日本語に翻訳してください。料理名は日本語で、価格は円表示にしてください'
});

// 多言語対応
const languages = ['英語', '中国語', '韓国語'];
const translatedImages = await Promise.all(
  languages.map(lang => 
    editor.editText({
      image: './japanese-poster.jpg',
      prompt: `すべてのテキストを${lang}に翻訳してください`
    })
  )
);

テキストの修正

// スペルミスの修正
const result = await editor.editText({
  image: './advertisement.jpg',
  prompt: 'スペルミスを修正してください。「セール中」が「セール中」になっているはずです'
});

// フォーマットの統一
const result = await editor.editText({
  image: './price-list.jpg',
  prompt: 'すべての価格表示を「¥1,000」の形式に統一してください'
});

🎨 要素の追加

ロゴの追加

// 会社ロゴの追加
const result = await editor.editElement({
  image: './product-photo.jpg',
  prompt: '右下角に小さな会社ロゴを追加してください。既存の要素と重ならないようにしてください'
});

// ブランドロゴの追加
const result = await editor.editElement({
  image: './marketing-banner.jpg',
  prompt: '左上角にブランドロゴを追加し、背景を半透明の白にしてください'
});

透かしの追加

// 著作権透かし
const result = await editor.editElement({
  image: './photo.jpg',
  prompt: '中央に半透明の「© 2024 会社名」という透かしを追加してください'
});

// サンプル透かし
const result = await editor.editElement({
  image: './demo-image.jpg',
  prompt: '対角線上に「SAMPLE」という大きな透かしを追加してください'
});

価格タグの追加

// セール価格タグ
const result = await editor.editElement({
  image: './product-image.jpg',
  prompt: '左上角に赤い「30% OFF」のセールタグを追加してください'
});

// 新商品バッジ
const result = await editor.editElement({
  image: './new-product.jpg',
  prompt: '右上角に金色の「NEW」バッジを追加してください'
});

情報要素の追加

// QRコードの追加
const result = await editor.editElement({
  image: './poster.jpg',
  prompt: '右下角にQRコードを追加し、その下に「詳細はこちら」というテキストを追加してください'
});

// 評価星の追加
const result = await editor.editElement({
  image: './product-review.jpg',
  prompt: '商品名の下に5つ星評価(4.5星)を追加してください'
});

🎭 高度なスタイル転送

芸術的スタイル

// 油絵風
const result = await editor.transferStyle({
  image: './portrait.jpg',
  style: 'oil-painting',
  intensity: 0.8
});

// 水彩画風
const result = await editor.transferStyle({
  image: './landscape.jpg',
  style: 'watercolor',
  intensity: 0.6
});

// アニメ風
const result = await editor.transferStyle({
  image: './character.jpg',
  style: 'anime',
  intensity: 0.7
});

写真スタイル

// ヴィンテージ風
const result = await editor.transferStyle({
  image: './modern-photo.jpg',
  style: 'vintage',
  intensity: 0.5
});

// モノクロ
const result = await editor.transferStyle({
  image: './color-photo.jpg',
  style: 'black-white',
  intensity: 1.0
});

// セピア調
const result = await editor.transferStyle({
  image: './photo.jpg',
  style: 'sepia',
  intensity: 0.6
});

📦 バッチ処理

商品カタログの更新

import pLimit from 'p-limit';
import pRetry from 'p-retry';

// 同時実行数を制限
const limit = pLimit(3);

async function updateProductCatalog(products) {
  const results = [];
  
  for (const product of products) {
    const result = await limit(async () => {
      return await pRetry(async () => {
        return await editor.editText({
          image: product.imagePath,
          prompt: `価格を「${product.oldPrice}」から「${product.newPrice}」に変更してください`
        });
      }, {
        retries: 3,
        onFailedAttempt: error => {
          console.log(`商品 ${product.name} の処理に失敗しました。再試行中... (${error.attemptNumber}/${error.retriesLeft + error.attemptNumber})`);
        }
      });
    });
    
    results.push({
      productName: product.name,
      originalImage: product.imagePath,
      updatedImage: result.imageUrl,
      credits: result.credits
    });
    
    console.log(`✅ ${product.name} の価格を更新しました`);
  }
  
  return results;
}

// 使用例
const products = [
  { name: 'スマートフォン', imagePath: './phone.jpg', oldPrice: '¥89,800', newPrice: '¥79,800' },
  { name: 'ノートパソコン', imagePath: './laptop.jpg', oldPrice: '¥149,800', newPrice: '¥129,800' },
  { name: 'タブレット', imagePath: './tablet.jpg', oldPrice: '¥59,800', newPrice: '¥49,800' }
];

const updatedCatalog = await updateProductCatalog(products);
console.log(`${updatedCatalog.length}個の商品を更新しました`);

多言語ローカライゼーション

async function localizeMarketingMaterials(basePath, targetLanguages) {
  const results = {};
  
  for (const language of targetLanguages) {
    try {
      const result = await editor.editText({
        image: basePath,
        prompt: `すべてのテキストを${language}に翻訳してください。文化的に適切な表現を使用してください`
      });
      
      results[language] = {
        imageUrl: result.imageUrl,
        credits: result.credits,
        status: 'success'
      };
      
      console.log(`✅ ${language}版を作成しました`);
    } catch (error) {
      results[language] = {
        status: 'failed',
        error: error.message
      };
      
      console.error(`❌ ${language}版の作成に失敗しました:`, error.message);
    }
  }
  
  return results;
}

// 使用例
const targetLanguages = ['英語', '中国語', '韓国語', 'スペイン語', 'フランス語'];
const localizedMaterials = await localizeMarketingMaterials(
  './japanese-ad.jpg',
  targetLanguages
);

// 結果の確認
Object.entries(localizedMaterials).forEach(([language, result]) => {
  if (result.status === 'success') {
    console.log(`${language}: ${result.imageUrl}`);
  } else {
    console.log(`${language}: 失敗 - ${result.error}`);
  }
});

🛍️ Eコマース用途

季節バリエーションの作成

async function createSeasonalVariants(productImage) {
  const seasons = [
    {
      name: '春',
      prompt: '背景を桜の花びらで装飾し、春らしいパステルカラーを追加してください',
      colors: ['ピンク', '薄緑', '白']
    },
    {
      name: '夏',
      prompt: '背景を青空と雲で装飾し、爽やかな夏らしい色合いにしてください',
      colors: ['青', '白', '黄色']
    },
    {
      name: '秋',
      prompt: '背景を紅葉で装飾し、温かみのある秋らしい色合いにしてください',
      colors: ['オレンジ', '赤', '茶色']
    },
    {
      name: '冬',
      prompt: '背景を雪の結晶で装飾し、クールな冬らしい色合いにしてください',
      colors: ['白', '青', '銀色']
    }
  ];
  
  const variants = [];
  
  for (const season of seasons) {
    const result = await editor.editElement({
      image: productImage,
      prompt: season.prompt
    });
    
    variants.push({
      season: season.name,
      imageUrl: result.imageUrl,
      colors: season.colors,
      credits: result.credits
    });
    
    console.log(`✅ ${season.name}バージョンを作成しました`);
  }
  
  return variants;
}

// 使用例
const seasonalProducts = await createSeasonalVariants('./base-product.jpg');
seasonalProducts.forEach(variant => {
  console.log(`${variant.season}: ${variant.imageUrl}`);
});

A/Bテスト用バリエーション

async function createABTestVariants(basePath) {
  const variants = [
    {
      name: 'バリアント A - 緊急性強調',
      prompt: '「限定セール!今すぐ購入」という赤い緊急性を強調するテキストを追加してください'
    },
    {
      name: 'バリアント B - 価値提案',
      prompt: '「高品質・低価格」という青い価値提案テキストを追加してください'
    },
    {
      name: 'バリアント C - 社会的証明',
      prompt: '「10,000人が選んだ」という緑の社会的証明テキストを追加してください'
    },
    {
      name: 'バリアント D - 特典強調',
      prompt: '「送料無料・即日配送」という紫の特典テキストを追加してください'
    }
  ];
  
  const results = await Promise.all(
    variants.map(async variant => {
      const result = await editor.editElement({
        image: basePath,
        prompt: variant.prompt
      });
      
      return {
        name: variant.name,
        imageUrl: result.imageUrl,
        credits: result.credits
      };
    })
  );
  
  return results;
}

// 使用例
const abTestImages = await createABTestVariants('./product-ad.jpg');
abTestImages.forEach(variant => {
  console.log(`${variant.name}: ${variant.imageUrl}`);
});

📚 教育用途

学習教材の適応

async function adaptEducationalMaterial(imagePath, targetAge, subject) {
  const agePrompts = {
    '小学生': 'テキストを小学生にも分かりやすい簡単な言葉に変更し、カラフルで親しみやすいデザインにしてください',
    '中学生': 'テキストを中学生レベルに調整し、学習意欲を高める現代的なデザインにしてください',
    '高校生': 'テキストを高校生レベルに調整し、洗練されたプロフェッショナルなデザインにしてください',
    '大学生': 'テキストを大学生レベルの専門的な内容に調整し、アカデミックなデザインにしてください'
  };
  
  const subjectPrompts = {
    '数学': '数式や図表を見やすく整理し、論理的な構造を強調してください',
    '理科': '実験や観察に関する要素を強調し、科学的な正確性を保ってください',
    '国語': '文章の構造を明確にし、読みやすいレイアウトにしてください',
    '英語': '英語学習に適した色分けやレイアウトを追加してください',
    '社会': '地図や年表などの視覚的要素を強調してください'
  };
  
  const combinedPrompt = `${agePrompts[targetAge]} また、${subjectPrompts[subject]}`;
  
  const result = await editor.editElement({
    image: imagePath,
    prompt: combinedPrompt
  });
  
  return result;
}

// 使用例
const adaptedMaterial = await adaptEducationalMaterial(
  './math-worksheet.jpg',
  '中学生',
  '数学'
);

console.log('適応された教材:', adaptedMaterial.imageUrl);

注釈付き図表の作成

async function createAnnotatedDiagram(imagePath, annotations) {
  let currentImage = imagePath;
  
  for (const annotation of annotations) {
    const result = await editor.editElement({
      image: currentImage,
      prompt: `${annotation.position}に「${annotation.text}」という注釈を追加してください。矢印で該当箇所を指してください`
    });
    
    currentImage = result.imageUrl;
    console.log(`注釈「${annotation.text}」を追加しました`);
  }
  
  return currentImage;
}

// 使用例
const annotations = [
  { position: '左上の心臓部分', text: '心房:血液を受け取る部屋' },
  { position: '左下の心臓部分', text: '心室:血液を送り出す部屋' },
  { position: '右側の血管', text: '大動脈:全身に血液を送る' },
  { position: '上部の血管', text: '肺動脈:肺に血液を送る' }
];

const annotatedDiagram = await createAnnotatedDiagram(
  './heart-diagram.jpg',
  annotations
);

console.log('注釈付き図表:', annotatedDiagram);

📱 ソーシャルメディア用途

複数フォーマットの作成

async function createSocialMediaFormats(basePath) {
  const formats = [
    {
      platform: 'Instagram投稿',
      size: { width: 1080, height: 1080 },
      prompt: 'Instagram用の正方形フォーマットに最適化し、視覚的に魅力的なレイアウトにしてください'
    },
    {
      platform: 'Instagramストーリー',
      size: { width: 1080, height: 1920 },
      prompt: 'Instagramストーリー用の縦長フォーマットに最適化し、上部にスペースを確保してください'
    },
    {
      platform: 'Twitter投稿',
      size: { width: 1200, height: 675 },
      prompt: 'Twitter用の横長フォーマットに最適化し、テキストを読みやすくしてください'
    },
    {
      platform: 'Facebook投稿',
      size: { width: 1200, height: 630 },
      prompt: 'Facebook用に最適化し、エンゲージメントを高める要素を追加してください'
    },
    {
      platform: 'LinkedIn投稿',
      size: { width: 1200, height: 627 },
      prompt: 'LinkedIn用にプロフェッショナルなデザインに調整してください'
    }
  ];
  
  const results = [];
  
  for (const format of formats) {
    // まず要素を編集
    const editedResult = await editor.editElement({
      image: basePath,
      prompt: format.prompt
    });
    
    // 次にサイズを調整
    const resizedResult = await editor.resizeImage({
      image: editedResult.imageUrl,
      width: format.size.width,
      height: format.size.height,
      mode: 'fit'
    });
    
    results.push({
      platform: format.platform,
      imageUrl: resizedResult.imageUrl,
      size: format.size
    });
    
    console.log(`✅ ${format.platform}用フォーマットを作成しました`);
  }
  
  return results;
}

// 使用例
const socialFormats = await createSocialMediaFormats('./campaign-image.jpg');
socialFormats.forEach(format => {
  console.log(`${format.platform}: ${format.imageUrl}`);
});

A/Bテスト用コンテンツ

async function createSocialABTests(basePath) {
  const testVariants = [
    {
      name: 'エモーショナル',
      prompt: '感情に訴える温かみのある色合いとフレンドリーなテキストスタイルにしてください'
    },
    {
      name: 'ロジカル',
      prompt: 'データと事実を強調するクールで論理的なデザインにしてください'
    },
    {
      name: 'ユーモラス',
      prompt: '楽しく親しみやすい雰囲気で、ユーモアを感じさせるデザインにしてください'
    },
    {
      name: 'プレミアム',
      prompt: '高級感と品質を強調する洗練されたエレガントなデザインにしてください'
    }
  ];
  
  const results = await Promise.all(
    testVariants.map(async variant => {
      const result = await editor.editElement({
        image: basePath,
        prompt: variant.prompt
      });
      
      return {
        variant: variant.name,
        imageUrl: result.imageUrl,
        credits: result.credits
      };
    })
  );
  
  return results;
}

// 使用例
const abTestContent = await createSocialABTests('./social-base.jpg');
abTestContent.forEach(test => {
  console.log(`${test.variant}バリアント: ${test.imageUrl}`);
});

🔄 ワークフロー自動化

コンテンツパイプライン

class ContentPipeline {
  constructor(editor) {
    this.editor = editor;
    this.steps = [];
  }
  
  addStep(name, processor) {
    this.steps.push({ name, processor });
    return this;
  }
  
  async process(inputImage) {
    let currentImage = inputImage;
    const results = [];
    
    for (const step of this.steps) {
      try {
        console.log(`🔄 実行中: ${step.name}`);
        const result = await step.processor(currentImage);
        
        currentImage = result.imageUrl || result;
        results.push({
          step: step.name,
          result: result,
          status: 'success'
        });
        
        console.log(`✅ 完了: ${step.name}`);
      } catch (error) {
        console.error(`❌ エラー: ${step.name} - ${error.message}`);
        results.push({
          step: step.name,
          error: error.message,
          status: 'failed'
        });
        
        // エラーが発生した場合、パイプラインを停止
        break;
      }
    }
    
    return {
      finalImage: currentImage,
      steps: results
    };
  }
}

// パイプラインの設定
const pipeline = new ContentPipeline(editor)
  .addStep('品質向上', async (image) => {
    return await editor.enhanceImage({
      image,
      enhancements: ['quality', 'sharpness']
    });
  })
  .addStep('ブランディング', async (image) => {
    return await editor.editElement({
      image,
      prompt: '右下角に会社ロゴを追加してください'
    });
  })
  .addStep('価格更新', async (image) => {
    return await editor.editText({
      image,
      prompt: '価格を最新のセール価格に更新してください'
    });
  })
  .addStep('透かし追加', async (image) => {
    return await editor.editElement({
      image,
      prompt: '中央に半透明の著作権透かしを追加してください'
    });
  });

// パイプラインの実行
const result = await pipeline.process('./raw-product.jpg');

console.log('最終画像:', result.finalImage);
console.log('処理ステップ:');
result.steps.forEach(step => {
  console.log(`  ${step.step}: ${step.status}`);
});

🚀 パフォーマンス最適化

インテリジェントキャッシュ

class ImageEditCache {
  constructor() {
    this.cache = new Map();
    this.maxSize = 100;
  }
  
  generateKey(image, prompt, options = {}) {
    const crypto = require('crypto');
    const data = JSON.stringify({ image, prompt, options });
    return crypto.createHash('md5').update(data).digest('hex');
  }
  
  get(image, prompt, options) {
    const key = this.generateKey(image, prompt, options);
    const cached = this.cache.get(key);
    
    if (cached && Date.now() - cached.timestamp < 24 * 60 * 60 * 1000) { // 24時間
      console.log('🎯 キャッシュヒット');
      return cached.result;
    }
    
    return null;
  }
  
  set(image, prompt, options, result) {
    const key = this.generateKey(image, prompt, options);
    
    // キャッシュサイズ制限
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    
    this.cache.set(key, {
      result,
      timestamp: Date.now()
    });
  }
}

// キャッシュ付きエディタークラス
class CachedImageEditor {
  constructor(editor) {
    this.editor = editor;
    this.cache = new ImageEditCache();
  }
  
  async editText(options) {
    const cached = this.cache.get(options.image, options.prompt, options);
    if (cached) {
      return cached;
    }
    
    const result = await this.editor.editText(options);
    this.cache.set(options.image, options.prompt, options, result);
    
    return result;
  }
  
  async editElement(options) {
    const cached = this.cache.get(options.image, options.prompt, options);
    if (cached) {
      return cached;
    }
    
    const result = await this.editor.editElement(options);
    this.cache.set(options.image, options.prompt, options, result);
    
    return result;
  }
}

// 使用例
const cachedEditor = new CachedImageEditor(editor);

// 最初の呼び出し(APIを使用)
const result1 = await cachedEditor.editText({
  image: './product.jpg',
  prompt: 'ロゴを追加してください'
});

// 2回目の呼び出し(キャッシュを使用)
const result2 = await cachedEditor.editText({
  image: './product.jpg',
  prompt: 'ロゴを追加してください'
});

堅牢なエラーハンドリング

import pRetry from 'p-retry';

class RobustImageEditor {
  constructor(editor, options = {}) {
    this.editor = editor;
    this.retryOptions = {
      retries: 3,
      factor: 2,
      minTimeout: 1000,
      maxTimeout: 10000,
      ...options.retry
    };
  }
  
  async editWithRetry(method, options) {
    return await pRetry(async () => {
      try {
        return await this.editor[method](options);
      } catch (error) {
        // 再試行可能なエラーかチェック
        if (this.isRetryableError(error)) {
          console.log(`再試行可能なエラー: ${error.message}`);
          throw error;
        } else {
          // 再試行不可能なエラーは即座に失敗
          console.error(`再試行不可能なエラー: ${error.message}`);
          throw new pRetry.AbortError(error.message);
        }
      }
    }, {
      ...this.retryOptions,
      onFailedAttempt: error => {
        console.log(`試行 ${error.attemptNumber} 失敗。${error.retriesLeft} 回再試行します...`);
      }
    });
  }
  
  isRetryableError(error) {
    const retryableCodes = [
      'NETWORK_ERROR',
      'TIMEOUT',
      'RATE_LIMIT_EXCEEDED',
      'SERVER_ERROR',
      'SERVICE_UNAVAILABLE'
    ];
    
    return retryableCodes.includes(error.code) || 
           error.message.includes('timeout') ||
           error.message.includes('network');
  }
  
  async editText(options) {
    return await this.editWithRetry('editText', options);
  }
  
  async editElement(options) {
    return await this.editWithRetry('editElement', options);
  }
  
  async transferStyle(options) {
    return await this.editWithRetry('transferStyle', options);
  }
}

// 使用例
const robustEditor = new RobustImageEditor(editor, {
  retry: {
    retries: 5,
    factor: 1.5
  }
});

try {
  const result = await robustEditor.editText({
    image: './image.jpg',
    prompt: 'テキストを編集してください'
  });
  
  console.log('編集成功:', result.imageUrl);
} catch (error) {
  console.error('すべての再試行が失敗しました:', error.message);
}

🎯 次のステップ

これらの例を参考に、あなたのプロジェクトに最適な実装を見つけてください:

📖 API リファレンス

すべてのメソッドとパラメータの詳細

API ドキュメント →

⚙️ 設定

パフォーマンス最適化と高度な設定

設定ガイド →

🚀 高度な機能

非同期処理とバッチ操作

高度な機能 →

🛠️ トラブルシューティング

よくある問題と解決方法

トラブルシューティング →

質問がありますか? サポートチームにお気軽にお問い合わせください。