How to Automate Image Processing: Claude Code 활용 가이드
automate image processing: Claude Code 활용. 실용적인 코드 예시와 단계별 가이드를 포함합니다.
이미지処理の자동화にClaude Codeを활용する
Web앱では이미지のリサイズ、フォーマット変換、최적화が頻繁に필요합니다。Claude Code를 활용하면 Sharp라이브러리を활용した이미지処理파이프라인を효율적으로구축할 수 있습니다。
Basics: 이미지リサイズと최적화
> Sharpを使って이미지のリサイズ・WebP変換・メタ데이터Deleteを行うユーティリティを作って。
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,
};
}
반응형이미지の一括생성
複数サイズの이미지を一度に생성して、<picture> 要素やsrcsetに대응させます。
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;
}
バッチ処理スクリプト
폴더内の이미지を一括処理する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}件の画像を処理します...`);
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이미지の動的생성
ブ로그글のOGP이미지を自動생성する機能も作れます。
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) =>
({ "<": "<", ">": ">", "&": "&", "'": "'", '"': """ })[c] || c
);
}
이미지処理と組み合わせて使えるPDF생성에 대해서는PDF생성機能를 확인하세요.Claude Codeの기본적인使い方は入門가이드를 참고하세요.
정리
Claude Code를 활용하면 이미지リサイズ、フォーマット変換、반응형대응、OGP생성まで、이미지処理에 관한機能を短시간で구현할 수 있습니다。要件を自然言語で伝える만으로、Sharpの複雑なAPIを적절하게使ったコードが得られます。
자세한 내용은Claude Code공식 문서를 확인하세요.
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code 다국어 글을 매일 발행하기 전에 확인할 7가지
누락된 언어, 깨진 CTA, 반영되지 않은 배포를 막기 위해 다국어 Claude Code 글을 매일 발행하기 전에 확인할 체크리스트입니다.
Codex Automations란? 잠자는 동안 AI가 콘텐츠 운영을 처리하게 하는 방법
Codex Automations로 트래픽 분석, 주제 선정, 글 작성, CTA 개선, 배포까지 자동화하는 실전 가이드.
Claude Code × GCP Cloud Functions 완전 가이드 | 서버리스 함수 초고속 개발
Claude Code로 GCP Cloud Functions를 효율화. HTTP/Pub/Sub/Firestore 트리거 구현부터 로컬 테스트·배포 자동화까지, Masa의 실무 경험을 토대로 실제 코드로 해설.