Introduction
Convert uploaded images to appropriate sizes and formats for fast CDN delivery — let Claude Code design Sharp + S3 + CloudFront pipeline.
CLAUDE.md Rules
## Image Processing Rules
- Format: WebP (JPEG fallback for unsupported)
- Sizes: thumb(100px), small(300px), medium(600px), large(1200px)
- Quality: WebP 80%, JPEG 85%
- Security: magic bytes validation, virus scan
- Max size: 10MB
- Async: queue-based processing after upload
Generated Implementation
export class ImageProcessor {
async processAndStore(params: { sourceKey: string; imageId: string }) {
const sourceBuffer = await this.downloadFromS3(params.sourceKey);
// Virus scan first
const scanResult = await scanForViruses(sourceBuffer);
if (!scanResult.clean) throw new SecurityError('Malware detected');
const sharpInstance = sharp(sourceBuffer);
// Generate all sizes in parallel
await Promise.all(
Object.entries(SIZE_CONFIG).map(async ([sizeName, config]) => {
const resized = await sharpInstance.clone()
.resize(config.width, config.height, {
fit: sizeName === 'thumb' ? 'cover' : 'inside',
position: 'attention', // Face-aware cropping
withoutEnlargement: true,
})
.webp({ quality: 80, effort: 4 })
.toBuffer();
const key = `images/${year}/${month}/${imageId}/${sizeName}.webp`;
await s3.send(new PutObjectCommand({
Key: key, Body: resized, ContentType: 'image/webp',
CacheControl: 'public, max-age=31536000, immutable',
}));
})
);
}
}
// Upload validation: magic bytes check
function isValidImageMagicBytes(bytes: Buffer): boolean {
if (bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) return true; // JPEG
if (bytes[0] === 0x89 && bytes[1] === 0x50) return true; // PNG
if (bytes[0] === 0x47 && bytes[1] === 0x49) return true; // GIF
return false;
}
Summary
- Sharp clone(): read once, convert to multiple sizes in parallel
- Magic bytes validation: catch Content-Type spoofing
- S3 CacheControl immutable: maximize CDN hit rate
- 202 Accepted: async processing after upload
Review with **Code Review Pack (¥980)* at prompt-works.jp*
myouga (@myougatheaxo) — Axolotl VTuber.
Top comments (0)