Nodejs image verification code captchapng

Nodejs project, encountered a problem when doing image verification code. Nodejs has no image library, there will be in the future, but not now.

Searching around on the Internet, there are several solutions:

1. Using a third-party verification code program, sometimes, the project may not allow it;

2. Use Java or PHP to generate pictures, call Nodejs, and use Redies to share in the middle;

These two methods are not ideal. Fortunately, I finally found a library that can support Nodejs image verification code. Although it only supports numbers, it is not bad. The principle is to use the Base64 picture encoding method.

The Gighub address for this library is: https://github.com/GeorgeChan/captchapng

The method of use is available on this homepage, here is to add:

1. Add captchapng module to package.json of Node project ;

2. Use the following code:

        var captchapng=require('captchapng');
        /*验证码*/
        router.get('/captchapng',function(req,res,next){
            var code = Math.floor(Math.random()*(9999-999+1)+999);  //生成随机验证码
            req.session.code = code;  //session设置code
            var p = new captchapng(80,30,parseInt(code)); // width,height,numeric captcha
            p.color(255, 255, 255, 0);  // First color: background (red, green, blue, alpha)
            p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)
            var img = p.getBase64();
            var imgbase64 = new Buffer(img,'base64');
            res.writeHead(200, {
                'Content-Type': 'image/png'
            });
            res.end(imgbase64);
        })

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325308606&siteId=291194637