koa2 验证码
在node.js环境中配合express框架制作验证码
效果图:

以下方法在ubuntu下进行的
安装:
npm install ccap --save
express制作验证码图片:
var ccap = require('ccap')();
var obj={};
//验证码
router.get('/code_img', function(req, res, next) {
var ary = ccap.get();
var txt = ary[0];
var buf = ary[1];
res.end(buf) //显示验证码图片
obj.code=txt; //验证码数字
});
其他模块调用获取验证码数字使用:obj.code
显示验证码图片:
<img src="code_img" onclick="this.src='code_img?'+Math.random();">
koa2验证码
安装:
npm install ccap --save
var ccap = require('ccap')();
router.get('/code_img', async function (ctx, next) {
return next().then(() => {
let ary = ccap.get();
let txt = ary[0];
let buf = ary[1];
ctx.body = buf; //直接输出图片
ctx.type = 'image/png';
ctx.session.captcha = txt; //这里可能需要加载session模块,输出验证码,在别的模块调用参与登陆逻辑验证
});
})
推荐使用
npm install gd-bmp
调用:
var fs = require('fs');
const BMP24 = require('gd-bmp').BMP24;//gd-bmp
//仿PHP的rand函数
function rand(min, max) {
return Math.random()*(max-min+1) + min | 0; //特殊的技巧,|0可以强制转换为整数
}
//制造验证码图片
function makeCapcha() {
var img = new BMP24(100, 40);
img.drawCircle(rand(0, 100), rand(0, 40), rand(10 , 40), rand(0, 0xffffff));
//边框
img.drawRect(0, 0, img.w-1, img.h-1, rand(0, 0xffffff));
img.fillRect(rand(0, 100), rand(0, 40), rand(10, 35), rand(10, 35), rand(0, 0xffffff));
img.drawLine(rand(0, 100), rand(0, 40), rand(0, 100), rand(0, 40), rand(0, 0xffffff));
//return img;
//画曲线
var w=img.w/2;
var h=img.h;
var color = rand(0, 0xffffff);
var y1=rand(-5,5); //Y轴位置调整
var w2=rand(10,15); //数值越小频率越高
var h3=rand(4,6); //数值越小幅度越大
var bl = rand(1,5);
for(var i=-w; i<w; i+=0.1) {
var y = Math.floor(h/h3*Math.sin(i/w2)+h/2+y1);
var x = Math.floor(i+w);
for(var j=0; j<bl; j++){
img.drawPoint(x, y+j, color);
}
}
var p = "ABCDEFGHKMNPQRSTUVWXYZ3456789";
var str = '';
for(var i=0; i<5; i++){
str += p.charAt(Math.random() * p.length |0);
}
var fonts = [BMP24.font8x16, BMP24.font12x24, BMP24.font16x32];
var x = 15, y=8;
for(var i=0; i<str.length; i++){
var f = fonts[Math.random() * fonts.length |0];
y = 8 + rand(-10, 10);
img.drawChar(str[i], x, y, f, rand(0, 0xffffff));
x += f.w + rand(2, 8);
}
return {img:img,font:str};
}
router.get('/code_img', async function (ctx, next) {
return next().then(() => {
var img = makeCapcha();
ctx.body = img.img.getFileData();
ctx.type = 'image/bmp';
ctx.session.captcha = img.font;
});
})
https://github.com/zengming00/node-gd-bmp
node-gd-bmp-master 验证码文件
最新文件,解压直接用
链接:https://pan.baidu.com/s/1It0W-57R-gX0PY8qAIyuJA?pwd=zauz
提取码:zauz
–来自百度网盘超级会员V5的分享