将base64转换为图片,仅在浏览器上显示

Convert base64 to image and display on browser only

我知道已经有人问过这个问题,但没有针对我的情况的单一解决方案。我正在使用三个字母的 JavaScript 生成验证码,我能够将它们转换为 base64 字符串,以便能够将其进一步转换为图像文件并显示在浏览器上。我无法将 base64 格式转换为图像格式。我可以使用 Google 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('')
}

您可以在 canvas 元素上绘制文本,然后从 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);