如何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 发送给你。
我们会严格保护你的个人信息,绝不发送垃圾邮件。
把 Claude Code 变成真正能带来结果的工作流
先领取中文说明的免费 PDF,再进入英文商品页选择合适的教材。如果你需要团队落地、流程设计或内容变现支持,也可以直接咨询。
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
每天发布多语言 Claude Code 文章前,要先检查的 7 件事
一份实用清单,帮助你每天发布多语言 Claude Code 文章时避免漏语言、CTA 错位和线上内容未更新。
Codex Automations 是什么?让 AI 在你睡觉时完成内容运营
用 Codex Automations 自动查看流量、选择主题、写文章、改善转化路径并部署网站的实用指南。
Claude Code × GCP Cloud Functions 完全指南 | 极速开发无服务器函数
用 Claude Code 高效开发 GCP Cloud Functions。从 HTTP/Pub/Sub/Firestore 触发器实现到本地测试、部署自动化,基于 Masa 的实战经验,附完整可运行代码示例。