Nodejs project, when doing the picture verification code encountered a problem. Nodejs There is no picture library, there will be later, but not now.
Search the network for a lap, there are several solutions:
1, the use of third-party verification code procedures, sometimes, the project may not be allowed;
2, using Java or PHP to generate images, Nodejs call, the middle of the use of redies sharing;
Both of these methods are not ideal, but finally found a can support Nodejs image verification Code of a library, although only support numbers, but also good. The principle is to use the Base64 image encoding method.
The Gighub address for this library is: https://github.com/GeorgeChan/captchapng
How to use this home page, here is a supplement:
1, add Captchapng module in the Package.json of node project;
2. Use the following code:
/** * Image Verification Code * @param req * @param res * @param next */function randomcodepngcontroller (Req , res , next) { var code = ' 0123456789 '; 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 to this controller, the page can be directly added to the img tag src attribute.
This will take care of the Nodejs image verification code, hope that Nodejs as soon as possible to supplement the lack of libraries.
"Nodejs Project Notes" Nodejs use the picture Verification code, Captchapng module can solve Nodejs image verification code