feat: 实现模板、艺术品建档、溯源节点与证书水印
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
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<Buffer> {
|
||||
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 = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<pattern id="wm" width="${tileW}" height="${tileH}" patternUnits="userSpaceOnUse" patternTransform="rotate(-28)">
|
||||
<text x="10" y="${Math.round(tileH / 2)}" font-family="Microsoft YaHei, SimHei, sans-serif" font-size="${fontSize}" fill="rgba(255,255,255,0.38)" stroke="rgba(0,0,0,0.12)" stroke-width="0.5">${safe}</text>
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#wm)" />
|
||||
</svg>`;
|
||||
|
||||
return image
|
||||
.composite([{ input: Buffer.from(svg), top: 0, left: 0 }])
|
||||
.jpeg({ quality: 86 })
|
||||
.toBuffer();
|
||||
}
|
||||
Reference in New Issue
Block a user