Use the captchapng module in Nodejs to generate an image verification code,
The Nodejs project encountered a problem when performing image verification code. Nodejs does not have a picture library. It will be available in the future, but it does not exist now.
There are several solutions to search around the network:
1. Use a third-party verification code program. In some cases, the project may not be allowed;
2. Use Java or PHP to generate images. Nodejs calls and use Redies for sharing;
These two methods are not ideal. Fortunately, I finally found a library that supports Nodejs image verification codes. Although only numbers are supported, they are not bad. The principle is to use Base64 image encoding.
The Gighub address for this library is: https://github.com/GeorgeChan/captchapng
The usage method is available on this homepage. Here we will add:
1. Add the captchapng module to the package. json of the Node project;
2. Use the following code:
/*** Image Verification code ** @ param req * @ param res * @ param next */function randomcodePngController (req, res, next) {var code = '2016 '; var length = 4; var randomcode = ''; for (var I = 0; I <length; I ++) {randomcode + = code [parseInt (Math. random () * 1000) % code. length];} // save to session if (null = req. session [sessionConstant. login]) {req. session [sessionConstant. login] ={};} req. session [sessionConstant. login] [sessionConstant. randomcode] = randomcode; // output image var p = new captchapng (80, 30, parseInt (randomcode); // 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 );}
3. Write a path for the controller, and the page can directly add the src attribute to the img label.
In this way, the image Verification Code of Nodejs is completed, and Nodejs is expected to supplement the missing library as soon as possible.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.