refactor code

This commit is contained in:
b1ek 2023-06-24 03:12:57 +10:00
parent 5bfad661ef
commit e1f2fdffbf
Signed by: blek
GPG Key ID: 14546221E3595D0C
1 changed files with 30 additions and 28 deletions

View File

@ -28,6 +28,32 @@ const get_size = (ratio, dpi, txtlen, padding) => {
} }
} }
const createImage = async (width, height, bg = 'white', options = {}) => {
return sharp({
create: {
width: width,
height: height,
channels: 3,
background: bg,
...options
}
})
}
const drawText = (pic, text, dpi, blend, options = {}) => {
return pic.composite([{
input: {
text: {
text,
font: 'Open Sans',
dpi,
rgba: true,
...options
}
},
blend
}])
}
/** @param {import('fastify').FastifyInstance} fastify */ /** @param {import('fastify').FastifyInstance} fastify */
module.exports = (fastify) => { module.exports = (fastify) => {
fastify.get('/captcha/v1/:text', async (req, res) => { fastify.get('/captcha/v1/:text', async (req, res) => {
@ -40,34 +66,13 @@ module.exports = (fastify) => {
console.log(size) console.log(size)
console.log(settings) console.log(settings)
let pic = (await sharp({ let pic = await createImage(size.width, size.height);
create: {
width: size.width,
height: size.height,
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 0 }
}
}));
drawText(pic, text, settings.dpi, 'over');
pic.composite([
{
input: {
text: {
text: text,
font: 'Arial',
dpi: settings.dpi,
rgba: true
}
},
blend: 'over',
gravity: 0
}
]);
const textpic = await pic const textpic = await pic
.ensureAlpha() .ensureAlpha()
.toFormat('png', { compressionLevel: 6 }) .toFormat('png', { compressionLevel: 0 })
.toBuffer(); .toBuffer();
const draw = canvas.createCanvas(size.width, size.height); const draw = canvas.createCanvas(size.width, size.height);
@ -75,16 +80,13 @@ module.exports = (fastify) => {
ctx.drawImage(await canvas.loadImage(textpic), 0, 0, size.width, size.height); ctx.drawImage(await canvas.loadImage(textpic), 0, 0, size.width, size.height);
const strokes = randint(25, 40); const strokes = randint(25, 40);
for (let i = 0; i != strokes; i++) { for (let i = 0; i < strokes; i++) {
ctx.strokeStyle = `rgba(0,0,0,${10})`; ctx.strokeStyle = `rgba(0,0,0,${10})`;
ctx.beginPath(); 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.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.stroke();
} }
ctx.bezierCurveTo(20, 20, 20, 30, 70, 25);
ctx.stroke();
res.header('Content-Type', 'png'); res.header('Content-Type', 'png');
return draw.toBuffer(); return draw.toBuffer();
}) })