Use Cases

Claude Code के साथ Automate Image Processing कैसे करें

Claude Code का उपयोग करके automate image processing सीखें। Practical code examples और step-by-step guidance शामिल है।

画像processingのautomationにClaude Codeをutilizationする

Webアプリでは画像のリsize、format変換、optimizationが頻繁にज़रूरी है।Claude Code का उपयोग करके、Sharplibraryをutilizationした画像processingpipelineをefficientlybuild किया जा सकता है。

Basics: 画像リsizeとoptimization

> Sharpका उपयोग करके画像のリsize・WebP変換・メタdataDeleteをकरनाutilityを作って。
import sharp from "sharp";
import path from "path";

interface ProcessOptions {
  width?: number;
  height?: number;
  quality?: number;
  format?: "webp" | "avif" | "jpeg" | "png";
}

export async function processImage(
  inputPath: string,
  outputDir: string,
  options: ProcessOptions = {}
) {
  const { width = 1200, height, quality = 80, format = "webp" } = options;
  const filename = path.basename(inputPath, path.extname(inputPath));
  const outputPath = path.join(outputDir, `${filename}.${format}`);

  let pipeline = sharp(inputPath)
    .resize(width, height, {
      fit: "inside",
      withoutEnlargement: true,
    })
    .removeMetadata();

  switch (format) {
    case "webp":
      pipeline = pipeline.webp({ quality });
      break;
    case "avif":
      pipeline = pipeline.avif({ quality });
      break;
    case "jpeg":
      pipeline = pipeline.jpeg({ quality, mozjpeg: true });
      break;
    case "png":
      pipeline = pipeline.png({ compressionLevel: 9 });
      break;
  }

  const info = await pipeline.toFile(outputPath);

  return {
    outputPath,
    width: info.width,
    height: info.height,
    size: info.size,
  };
}

responsive画像の一括generate

複数sizeの画像を一度にgenerateして、<picture> 要素やsrcsetにsupportさせ है।

interface ResponsiveSize {
  width: number;
  suffix: string;
}

const RESPONSIVE_SIZES: ResponsiveSize[] = [
  { width: 320, suffix: "sm" },
  { width: 640, suffix: "md" },
  { width: 1024, suffix: "lg" },
  { width: 1920, suffix: "xl" },
];

export async function generateResponsiveImages(
  inputPath: string,
  outputDir: string
) {
  const filename = path.basename(inputPath, path.extname(inputPath));
  const results = [];

  for (const size of RESPONSIVE_SIZES) {
    const outputPath = path.join(outputDir, `${filename}-${size.suffix}.webp`);

    const info = await sharp(inputPath)
      .resize(size.width, null, {
        fit: "inside",
        withoutEnlargement: true,
      })
      .webp({ quality: 80 })
      .toFile(outputPath);

    results.push({
      path: outputPath,
      width: info.width,
      height: info.height,
      size: info.size,
    });
  }

  return results;
}

バッチprocessingスクリプト

フォルダ内の画像を一括processingするCLIスクリプト है।

import fs from "fs/promises";
import path from "path";
import { processImage } from "./image-processor";

async function batchProcess(inputDir: string, outputDir: string) {
  await fs.mkdir(outputDir, { recursive: true });

  const files = await fs.readdir(inputDir);
  const imageFiles = files.filter((f) =>
    /\.(jpg|jpeg|png|gif|bmp|tiff)$/i.test(f)
  );

  console.log(`${imageFiles.length}件の画像をprocessingします...`);

  const results = await Promise.allSettled(
    imageFiles.map(async (file) => {
      const inputPath = path.join(inputDir, file);
      const result = await processImage(inputPath, outputDir, {
        width: 1200,
        quality: 80,
        format: "webp",
      });

      const originalSize = (await fs.stat(inputPath)).size;
      const reduction = ((1 - result.size / originalSize) * 100).toFixed(1);
      console.log(`  ${file} → ${path.basename(result.outputPath)} (${reduction}% 削減)`);
      return result;
    })
  );

  const succeeded = results.filter((r) => r.status === "fulfilled").length;
  const failed = results.filter((r) => r.status === "rejected").length;
  console.log(`完了: 成功 ${succeeded}件, 失敗 ${failed}件`);
}

// 実行
batchProcess("./images/raw", "./images/optimized");

OGP画像の動的generate

ブlog記事のOGP画像を自動generateするfeaturesも作れ है।

import sharp from "sharp";

export async function generateOgImage(title: string, outputPath: string) {
  const width = 1200;
  const height = 630;

  const svgText = `
    <svg width="${width}" height="${height}">
      <rect width="100%" height="100%" fill="#1e293b"/>
      <text x="50%" y="45%" text-anchor="middle" fill="white"
        font-size="48" font-family="sans-serif" font-weight="bold">
        ${escapeXml(title.length > 30 ? title.slice(0, 30) + "..." : title)}
      </text>
      <text x="50%" y="65%" text-anchor="middle" fill="#94a3b8"
        font-size="24" font-family="sans-serif">
        ClaudeCodeLab
      </text>
    </svg>
  `;

  await sharp(Buffer.from(svgText))
    .resize(width, height)
    .png()
    .toFile(outputPath);
}

function escapeXml(str: string) {
  return str.replace(/[<>&'"]/g, (c) =>
    ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&apos;", '"': "&quot;" })[c] || c
  );
}

画像processing के साथ combineて使えるPDFgenerateके बारे मेंはPDFgeneratefeaturesदेखें。Claude Codeのbasic use करने का तरीकाはintroduction guideをदेखें。

Summary

Claude Code का उपयोग करके、画像リsize、format変換、responsivesupport、OGPgenerate तक、画像processingに関するfeaturesをकम समय मेंimplementationでき है।要件を自然言語で伝える से ही、SharpのcomplexなAPIをappropriateに使ったcodeが得られ है।

विस्तार से जानने के लिएClaude Codeofficial documentationदेखें。

#Claude Code #image processing #Sharp #optimization #automation