refactor code
This commit is contained in:
parent
5bfad661ef
commit
e1f2fdffbf
58
routes.js
58
routes.js
|
@ -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 */
|
||||
module.exports = (fastify) => {
|
||||
fastify.get('/captcha/v1/:text', async (req, res) => {
|
||||
|
@ -40,34 +66,13 @@ module.exports = (fastify) => {
|
|||
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 }
|
||||
}
|
||||
}));
|
||||
let pic = await createImage(size.width, size.height);
|
||||
|
||||
|
||||
pic.composite([
|
||||
{
|
||||
input: {
|
||||
text: {
|
||||
text: text,
|
||||
font: 'Arial',
|
||||
dpi: settings.dpi,
|
||||
rgba: true
|
||||
}
|
||||
},
|
||||
blend: 'over',
|
||||
gravity: 0
|
||||
}
|
||||
]);
|
||||
drawText(pic, text, settings.dpi, 'over');
|
||||
|
||||
const textpic = await pic
|
||||
.ensureAlpha()
|
||||
.toFormat('png', { compressionLevel: 6 })
|
||||
.toFormat('png', { compressionLevel: 0 })
|
||||
.toBuffer();
|
||||
|
||||
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);
|
||||
|
||||
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.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();
|
||||
})
|
||||
|
|
Loading…
Reference in New Issue