我知道这个问题已被提出,但我的案例没有一个解决方案。我正在使用三个字母的JavaScript生成一个Captcha,我能够将它们转换为base64字符串,以便能够将其进一步转换为图像文件并在浏览器上显示。我无法将base64格式转换为图像格式。我可以使用谷歌reCaptcha,但我这样做是为了学习目的。所以任何帮助都会很棒! 这是我的JavaScript代码:
var code2 = ''
$('#captCha').ready(function Captcha() {
var alpha = new Array('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')
for (var i = 0; i < 6; i++) {
var a = alpha[Math.floor(Math.random() * alpha.length)]
var b = alpha[Math.floor(Math.random() * alpha.length)]
var c = alpha[Math.floor(Math.random() * alpha.length)]
}
var code = a + ' ' + b + ' ' + ' ' + c
code2 = removeSpaces(code)
var b64 = btoa(unescape(encodeURIComponent(code2)))
console.log(b64)
document.getElementById('captCha').innerHTML = b64
});
function removeSpaces (string) {
return string.split(' ').join('')
}
答案 0 :(得分:1)
您可以在canvas
元素上绘制文本,然后从画布中获取base64编码的图像:
const alpha = ['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 a = alpha[Math.floor(Math.random() * alpha.length)];
const b = alpha[Math.floor(Math.random() * alpha.length)];
const c = alpha[Math.floor(Math.random() * alpha.length)];
const code = a + ' ' + b + ' ' + c;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = '24px sans-serif';
context.fillText(code, 10, 50);
const img = document.createElement('img');
img.setAttribute('src', canvas.toDataURL());
document.body.appendChild(img);