__home
is project rootfontpath
=Arial.ttf
, copy from Windows
Created
November 21, 2016 14:21
-
-
Save magicdawn/f7dca2f8de039cb5b3800f1ea3fef0ff to your computer and use it in GitHub Desktop.
image captcha with node-gd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment