1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| const path = require('path'); const sharp = require('sharp'); const Text2SVG = require('text-to-svg');
async function nodeGenWatermark({ img, text, filepath }) {
function text2SVG({ text, fontSize = 72, color = 'rgba(204,204,204,0.45)' }) { const fontPath = path.resolve(__dirname, '../../assets/PingFang-SC-Regular.ttf'); const text2SVG = Text2SVG.loadSync(fontPath); const options = { fontSize, anchor: 'top', attributes: { fill: color }, }; const textSVG = text2SVG.getSVG(text, options); return Buffer.from(textSVG); }
async function rotateWatermarkBuffer(text) { const textBuffer = text2SVG({ text: ` ${text} ` }); return sharp(textBuffer) .rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 0 } }) .toBuffer(); }
async function init({ img, text, filepath }) { const textBuffer = await rotateWatermarkBuffer(text); const imgInfo = await sharp(img) .composite([{ input: textBuffer, tile: true }]) .toFile(filepath); return imgInfo; }
await init({ img, text, filepath }); }
nodeGenWatermark({ img: path.resolve(__dirname, '../../assets/chrome.png'), text: '水印', filepath: path.resolve(__dirname, '../../assets/output.png'), });
|