关于 image-processing
这是一份图像处理实践指南,提供 Node.js 的 Sharp、Cloudinary 和 Python Pillow 示例。内容涵盖常见上传转换与验证、响应式图像及生产实践,并非独立的图像处理服务。
主要功能
- 01使用 Sharp 调整尺寸和转换格式
- 02用 Express 与 multer 验证上传
- 03用 Python Pillow 处理图像
- 04使用 Cloudinary 托管图像处理
- 05响应式图像交付建议
- 06生产检查清单与反模式
适用场景
- 01上传时生成多种图像尺寸
- 02处理前验证文件类型和大小
- 03将上传图像转换为 WebP 或 AVIF
- 04规划后台处理和 CDN 分发
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill image-processing安装后在 Claude Code 中输入/image-processing确认已加载。
详细介绍
图像处理
Sharp(Node.js — 推荐)
import sharp from 'sharp';
// Resize and convert
async function processUpload(input: Buffer, filename: string) {
const variants = await Promise.all([
sharp(input).resize(1200, 1200, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 80 }).toBuffer(),
sharp(input).resize(400, 400, { fit: 'cover' })
.webp({ quality: 75 }).toBuffer(),
sharp(input).resize(100, 100, { fit: 'cover' })
.webp({ quality: 70 }).toBuffer(),
]);
return {
original: { buffer: variants[0], key: `images/${filename}.webp` },
medium: { buffer: variants[1], key: `images/${filename}-400.webp` },
thumb: { buffer: variants[2], key: `images/${filename}-100.webp` },
};
}
Express 上传处理流水线
import multer from 'multer';
const upload = multer({ limits: { fileSize: 10 * 1024 * 1024 } }); // 10MB
app.post('/api/images', upload.single('image'), async (req, res) => {
// Validate image type
const metadata = await sharp(req.file!.buffer).metadata();
if (!['jpeg', 'png', 'webp'].includes(metadata.format!)) {
return res.status(400).json({ error: 'Invalid image format' });
}
const variants = await processUpload(req.file!.buffer, uuid());
// Upload to S3
await Promise.all(Object.values(variants).map((v) =>
s3.putObject({ Bucket: BUCKET, Key: v.key, Body: v.buffer, ContentType: 'image/webp' })
));
res.json({ url: `${CDN_URL}/${variants.original.key}` });
});
Cloudinary(托管服务)
import { v2 as cloudinary } from 'cloudinary';
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET,
});
// Upload with auto-optimization
const result = await cloudinary.uploader.upload(filePath, {
folder: 'products',
transformation: [
{ width: 1200, height: 1200, crop: 'limit' },
{ quality: 'auto', fetch_format: 'auto' },
],
});
// URL-based transformations
const thumbUrl = cloudinary.url(result.public_id, {
width: 200, height: 200, crop: 'fill', gravity: 'face',
quality: 'auto', format: 'webp',
});
Python(Pillow)
from PIL import Image
from io import BytesIO
def process_image(data: bytes, max_size: int = 1200) -> bytes:
img = Image.open(BytesIO(data))
img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
output = BytesIO()
img.save(output, format='WEBP', quality=80)
return output.getvalue()
响应式图像(HTML)
<picture>
<source srcset="/images/hero-400.webp 400w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1024px) 800px, 1200px"
type="image/webp" />
<img src="/images/hero-800.jpg" alt="Hero image" loading="lazy" decoding="async" />
</picture>
反模式
| 反模式 | 修正方案 |
|---|---|
| 在请求处理程序中处理 | 在后台作业队列中处理 |
| 只存储原始尺寸 | 上传时生成多个尺寸 |
| 不转换格式 | 转换为 WebP/AVIF,以减小文件大小 |
| 不验证文件大小 | 处理前进行验证 |
| 从应用服务器提供图像 | 使用 CDN 或云存储 |
生产环境检查清单
- 在后台队列中处理图像
- 生成多种尺寸(缩略图、中等尺寸、完整尺寸)
- 转换为 WebP/AVIF,适配现代浏览器
- 使用 CDN 提供图像
- 验证文件类型和大小
- 为保护隐私而剥离元数据
评论
支持 Markdown