Convert base64 to image and display on browser only

1.4k Views Asked by At

I know that this question has already been asked but there's not a single solution for my case. I am generating a Captcha using JavaScript of three letters and I am able to convert them to base64 string so as to able to convert it further to an image file and display on the browser. I am not able to convert the base64 format to image format. I can use the Google reCaptcha but I am doing this for learning purpose. So any help would be great! This is my JavaScript code:

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('')
}
1

There are 1 best solutions below

1
On BEST ANSWER

You could draw the text on a canvas element and then get the base64-encoded image from the canvas:

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);