图形验证码 with node-gd
node-gd 是 libgd 的 node binding, gd 常用于 PHP 中 … 嫌 node-canvas 的 backend cario 依赖过多可以看下这个
验证码示例 https://gist.github.com/magicdawn/f7dca2f8de039cb5b3800f1ea3fef0ff
'use strict'
const fs = require('fs')
const _ = require('lodash')
const onecolor = require('onecolor')
const gd = require('node-gd')
// https://github.com/y-a-v-a/node-gd/blob/master/docs/index.md
// Set full path to font file
const fontpath = __home + '/files/fonts/arial.ttf'
/**
* 获取 Buffer
*/
exports.genBuffer = (function(text) {
const width = 100
const height = 40
const img = gd.createSync(width, height)
// Set background color
img.colorAllocateAlpha(255, 255, 255, 1)
// 验证码
drawString(text)
// 躁点
drawPoints()
// buf
// jpeg: 0-100, 质量
// png: 0-9
const buf = new Buffer(img.jpegPtr(50), 'binary')
img.destroy()
return buf
/**
* draw text
*/
function drawString() {
let x = 10
for (let c of text) {
const color = randomColor()
const size = _.random(18, 20)
const angle = _.random(-Math.PI / 6, Math.PI / 6)
const y = angle > 0 ? 30 : 20
img.stringFT(color, fontpath, size, angle, x, y, c)
x += size - 5
}
}
/**
* 躁点
*/
function drawPoints() {
for (let x = 0; x < 100; x += 10) {
for (let y = 0; y < 40; y += 10) {
img.filledEllipse(
_.random(0, width),
_.random(0, height),
2, 2, // 半径
randomColor()
)
}
}
}
/**
* 随机颜色
*/
function randomColor() {
return img.colorAllocate(
_.random(0, 255),
_.random(0, 255),
_.random(0, 255)
)
}
})
/**
* 获取 base64 表示
*/
exports.genBase64 = (function(text) {
const buf = exports.genBuffer(text)
return 'data:image/jpg;base64,' + buf.toString('base64')
})