1. 模块安装
npm install captchapng --save
2.使用示例
var http = require('http');var captchapng = require('captchapng'); http.createServer(function (request, response) { if(request.url == '/captcha.png') { var p = new captchapng(80,30,parseInt(Math.random()*9000+1000)); // 宽,高,数字验证码 p.color(0, 0, 0, 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'); response.writeHead(200, { 'Content-Type': 'image/png' }); response.end(imgbase64); } else response.end('');}).listen(8181); console.log('Web server started.\n http:\\127.0.0.1:8181\captcha.png');
3.在Express框架中使用
为了能在项目不同位置使用,我在方法中增加了query参数自定义宽高的设置。示例如下:
var captchapng = require('captchapng');exports.captchap=function (req, res, next) { var width=!isNaN(parseInt(req.query.width))?parseInt(req.query.width):100; var height=!isNaN(parseInt(req.query.height))?parseInt(req.query.height):30; var code = parseInt(Math.random()*9000+1000); req.session.checkcode = code; var p = new captchapng(width,height, code); p.color(0, 0, 0, 0); p.color(80, 80, 80, 255); var img = p.getBase64(); var imgbase64 = new Buffer(img,'base64'); res.writeHead(200, { 'Content-Type': 'image/png' }); res.end(imgbase64);}
在前端页面,调用方法对应路由即可。