How can you encode a string to Base64 in JavaScript?

前端 未结 26 4600
梦如初夏
梦如初夏 2020-11-21 04:02

I have a PHP script that can encode a PNG image to a Base64 string.

I\'d like to do the same thing using JavaScript. I know how to open files, but I\'m not sure how

26条回答
  •  深忆病人
    2020-11-21 05:04

    For my project I still need to support IE7 and work with large input to encode.

    Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.

    Here is the example for encode:

    var encode = function (input) {
        var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    
        input = _utf8_encode(input);
    
        while (i < input.length) {
    
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
    
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
    
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
    
            output.push(_keyStr.charAt(enc1));
            output.push(_keyStr.charAt(enc2));
            output.push(_keyStr.charAt(enc3));
            output.push(_keyStr.charAt(enc4));
    
        }
    
        return output.join("");
    };
    

提交回复
热议问题