import sharp from 'sharp'; function escapeXml(s: string): string { return s.replace(/[<>&'"]/g, (c) => { switch (c) { case '<': return '<'; case '>': return '>'; case '&': return '&'; case "'": return '''; case '"': return '"'; default: return c; } }); } // 在图片上平铺半透明文字水印,输出 JPEG。 export async function addWatermark(input: Buffer, text: string): Promise { const image = sharp(input).rotate(); // 处理 EXIF 方向 const meta = await image.metadata(); const width = meta.width || 1000; const height = meta.height || 1000; const fontSize = Math.max(18, Math.round(width / 24)); const tileW = Math.max(220, Math.round(width / 2)); const tileH = Math.max(120, Math.round(height / 5)); const safe = escapeXml(text); const svg = ` ${safe} `; return image .composite([{ input: Buffer.from(svg), top: 0, left: 0 }]) .jpeg({ quality: 86 }) .toBuffer(); }