代码改变世界

node 图片验证码生成

2018-03-12 20:22  muamaker  阅读(645)  评论(0编辑  收藏  举报

var captchapng = require('captchapng');
var http = require("http")


var server = http.createServer(imgCode);
// 获取验证码
function imgCode(req, res) {
var code = parseInt(Math.random() * 9000 + 1000, 10);

var p = new captchapng(80, 30, code); // width,height,numeric captcha
p.color(7, 93, 179,255); // First color: background (red, green, blue, alpha)
p.color(255, 255, 255, 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);
}

server.listen(3000,function(){
console.log('服务器启动成功!');
});