UNPKG

captcha-generator

Version:

Production image verification code by jpeglib

82 lines (65 loc) 2.66 kB
import fs from 'fs'; import path from 'path'; import hcaptha from '../build/Release/hcaptha.node'; const tmpPath = path.join(__dirname, "/tmp/"); !fs.existsSync(tmpPath) && fs.mkdirSync(tmpPath); const defaultDictionary = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", /*"l",*/ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", /*"I",*/ "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; const platform = process.platform; export function generate(text = createPlaintext(), width = 240, height = 112, charOffset = 0, fontSize = 100) { if (typeof text === "object") { const {text:t,width:w,height:h,charOffset:c,fontSize :f} = text; [text, width, height, charOffset, fontSize] = [t, w, h, c, f]; } const isJpeg = ~["linux"].indexOf(platform) ? 1 : 0; const tmpFilePath = path.join(tmpPath, `/${Math.random()}.${isJpeg ? "jpeg" : "bmp"}`); const defaultQuality = 60; charOffset = charOffset || width / text.length; hcaptha.create(text, tmpFilePath, text.length, width, height, charOffset, defaultQuality, isJpeg, fontSize); const buf = fs.readFileSync(tmpFilePath); fs.unlinkSync(tmpFilePath); return CImg(buf, text, isJpeg ? "jpeg" : "bmp"); } export function createPlaintext(count = 5, dictionary = defaultDictionary) { if (isNaN(count) || !(dictionary instanceof Array) || dictionary.length === 0) { throw Error("Parameter error"); } let i = 0, len = dictionary.length, textList = ""; while (i++ < count) { textList += dictionary[parseInt(Math.random() * len) % len]; } return textList; } function CImg(buf, text, type) { var obj = {}; return Object.defineProperties(obj, { buffer: { get: function () { return buf; }, enumerable: true, configurable: false }, plaintext: { get: function () { return text; }, enumerable: true, configurable: false }, imageType: { get: function () { return `image/${type}`; }, enumerable: true, configurable: false }, base64: { get: function () { return `data:image/${type};base64,${buf.toString("base64")}`; }, enumerable: true, configurable: false } }) } //hrobj.create("abcde", __dirname + "/c/" + start + ".bmp", 5, 240, 112, 50, 50, 0, 110);