Use Cases

Cara Automate Image Processing dengan Claude Code

Pelajari cara automate image processing menggunakan Claude Code. Dilengkapi contoh kode praktis dan panduan langkah demi langkah.

otomatisasiにClaude Codeをpemanfaatan gambarpemrosesan

Webaplikasi gambar リサイズ、formatkonversi、optimasi 頻繁 diperlukan.Claude Code 使えば、Sharplibrary pemanfaatan gambarpemrosesanpipeline efisien pembangunan bisa dilakukan.

Basics: gambarリサイズとoptimasi

> Sharp 使ってgambar リサイズ・WebPkonversi・metadataDelete 行うutilitas buatkan.
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,
  };
}

一括generate レスポンシブgambar

複数サイズ gambar 一度 generate 、<picture> elemenやsrcset dukunganさせ.

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;
}

バッチpemrosesanscript

フォルダ内 gambar 一括pemrosesan CLIscript.

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}件 gambar pemrosesanします...`);

  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(`selesai: berhasil ${succeeded}件, gagal ${failed}件`);
}

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

Generate Dinamis Gambar OGP

ブログartikel OGPgambar 自動generate 機能 juga 作れ.

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
  );
}

Untuk gambarpemrosesanと組み合わせて使えるPDFgenerateについてはPDFgenerate機能をご覧ください。Claude Codeのdasar的な使い方, lihat 入門ガイド.

Summary

Dengan Claude Code, gambarリサイズ、formatkonversi、レスポンシブdukungan、OGPgenerateま 、gambarpemrosesan 関 機能 waktu singkat implementasi bisa dilakukan.要件 自然言語 伝えるだけ 、Sharp kompleksなAPI tepat 使ったコード 得られ.

Untuk detail lebih lanjut, lihat Dokumentasi Resmi Claude Code.

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