const sharp = require('sharp'); const canvas = require('canvas'); const crypto = require('crypto'); const randint = (min, max) => { return crypto.randomInt(max) + min }; /** @param {import('fastify').FastifyRequest} req */ const getSettings = (req) => { const q = req.query; const settings = { // Width and height are ratio numbers; actual width & height is calculated from text length & padding width: q.width ?? 3, height: q.height ?? 1, padding: q.padding ?? 20, format: q.format ?? 'png', dpi: q.dpi ?? 250 }; for (const key in settings) { if (['format'].indexOf(key) !== -1) continue; settings[key] = parseInt(settings[key]); } return settings; } const get_size = (ratio, dpi, txtlen, padding) => { return { width: Math.floor((ratio[0] * dpi * 0.12) + (txtlen * dpi * 0.08)) + (padding * 2), height: Math.floor(ratio[1] * dpi * 0.2) + (padding * 2) } } /** @param {import('fastify').FastifyInstance} fastify */ module.exports = (fastify) => { fastify.get('/captcha/v1/:text', async (req, res) => { const text = req.params.text; const settings = getSettings(req); const size = get_size([settings.width, settings.height], settings.dpi, text.length, settings.padding); console.log(size) console.log(settings) let pic = (await sharp({ create: { width: size.width, height: size.height, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } })); pic.composite([ { input: { text: { text: text, font: 'Arial', dpi: settings.dpi, rgba: true } }, blend: 'over', gravity: 0 } ]); const textpic = await pic .ensureAlpha() .toFormat('png', { compressionLevel: 6 }) .toBuffer(); const draw = canvas.createCanvas(size.width, size.height); const ctx = draw.getContext('2d'); ctx.drawImage(await canvas.loadImage(textpic), 0, 0, size.width, size.height); const strokes = randint(25, 40); for (let i = 0; i != strokes; i++) { ctx.strokeStyle = `rgba(0,0,0,${10})`; ctx.beginPath(); ctx.bezierCurveTo(randint(0, size.width), randint(0, size.height), randint(0, size.width), randint(0, size.height), randint(0, size.width), randint(0, size.height)); ctx.stroke(); } ctx.bezierCurveTo(20, 20, 20, 30, 70, 25); ctx.stroke(); res.header('Content-Type', 'png'); return draw.toBuffer(); }) }