Shashank3736 / captcha-canvas

A captcha generator by using skia-canvas.
https://captcha-canvas.js.org
Apache License 2.0
61 stars 12 forks source link

.setBackground() not working (v2.3.1) #49

Closed AstrooKai closed 1 year ago

AstrooKai commented 1 year ago
const randomString = require('random-base64-string')
  const filename = randomString(10);
  const { CaptchaGenerator } = require("captcha-canvas");
  const { writeFileSync } = require('fs');
  const captcha = new CaptchaGenerator()
    .setDimension(150, 450) 
    .setCaptcha({size: 60, color: "#bd7a21"})
    .setBackground("./cdn/media/bsd-bg.jpg") //this image path is valid
    .setDecoy({opacity: 0.5})
    .setTrace({color: "#bd7a21"});
  const buffer = captcha.generateSync();
  writeFileSync(`./captcha/${filename}.png`, buffer);
  res.json({text: captcha.text, image: `https://eca-beta.astrookai.repl.co/captcha/${filename}.png`});

//ex: returns {"text":"DEEDDE","image":"https://eca-beta.astrookai.repl.co/captcha/rh5OF1CHuX.png"}

The code above generates a captcha image, the problem is that the .setBackground() doesn't add the image below as the background, is there a reason why this is happening? No errors are logged to the console when the code is executed.

Supposed background image image Actual Result image

Shashank3736 commented 1 year ago

You are using generateSync method to generate image. generateSync do not support setBackground customization see here in documentation. You have two option:

  1. Use generate method to generate captcha image.
  2. Pass your image through generateSync option
const { CaptchaGenerator, resolveImage } = require("captcha-canvas");
const fs = require("fs");
const img = await resolveImage("./path/to/file");

const captcha = new CaptchaGenerator()
.generateSync({background: img});

fs.writeFileSync("image.png", captcha);

My personal recommendation is to use method 1. As if I ever create v4, support for synchronous generation will be depreciated.

AstrooKai commented 1 year ago

Thank you for the fast response, this has also solved my problem. Though one question came to my mind, is there a way to generate an alphanumeric captcha or does the package supports this feature?

Shashank3736 commented 1 year ago

You can use crypto module to generate an alphanumeric captcha. crypto module comes with Node.js, and the package also use it to generate captchas.

// To generate random alphanumeric string
const { randomBytes } = require('crypto'); 
const randomString = randomBytes(10).toString('hex').substring(0, 6);
console.log(randomString); //will log a 6 character string in console