我有一个PHP脚本,可以将PNG图像编码为Base64字符串。

我想用JavaScript做同样的事情。我知道如何打开文件,但我不知道如何进行编码。我不习惯使用二进制数据。


当前回答

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

跨浏览器

// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

js小提琴


用node . js

下面是在Node.js中如何将普通文本编码为base64:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// The default is "utf8". Possible encoding types are "ascii", "utf8", "ucs2", "base64", "binary", and "hex"
var b = Buffer.from('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

下面是解码base64编码字符串的方法:

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

. js和

使用dojox.encoding.base64对字节数组进行编码:

var str = dojox.encoding.base64.encode(myByteArray);

解码一个base64编码的字符串:

var bytes = dojox.encoding.base64.decode(str)

安装angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope',
    function($base64, $scope) {

        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

其他回答

为了使Base64编码的字符串URL友好,在JavaScript中你可以这样做:

// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA=='; 

// make URL friendly:
str = str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');

// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');

参见这个小提琴:http://jsfiddle.net/magikMaker/7bjaT/

我宁愿使用CryptoJS中的Base64编码/解码方法,这是使用最佳实践和模式在JavaScript中实现的最流行的标准和安全加密算法库。

从下面的评论(由SET和Stefan Steiger)接受的答案,这里是一个快速总结如何编码/解码一个字符串到Base64,而不需要一个库。

str = "The quick brown fox jumps over the lazy dog";
b64 = btoa(unescape(encodeURIComponent(str)));
str = decodeURIComponent(escape(window.atob(b64)));

纯JavaScript演示

const input = document.getElementsByTagName('input')[0]; const btnConv = document.getElementById('btnConv'); const btnDeConv = document.getElementById('btnDeConv'); input.value = "The quick brown fox jumps over the lazy dog"; btnConv.addEventListener('click', () => { const txt = input.value; const b64 = btoa(unescape(encodeURIComponent(txt))); input.value = b64; btnDeConv.style.display = 'block'; btnConv.style.display = 'none'; }); btnDeConv.addEventListener('click', () => { var b64 = input.value; var txt = decodeURIComponent(escape(window.atob(b64))); input.value = txt; btnConv.style.display = 'block'; btnDeConv.style.display = 'none'; }); input{width:500px;} #btnDeConv{display:none;} <div><input type="text" /></div> <button id="btnConv">Convert</button> <button id="btnDeConv">DeConvert</button>

.

jQuery演示(使用jQuery库进行显示,但不用于编码/解码)

str = "The quick brown fox jumps over the lazy dog"; $('input').val(str); $('#btnConv').click(function(){ var txt = $('input').val(); var b64 = btoa(unescape(encodeURIComponent(txt))); $('input').val(b64); $('#btnDeConv').show(); }); $('#btnDeConv').click(function(){ var b64 = $('input').val(); var txt = decodeURIComponent(escape(window.atob(b64))); $('input').val(txt); }); #btnDeConv{display:none;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" /> <button id="btnConv">Convert</button> <button id="btnDeConv">DeConvert</button>

还看到:

Base64 - MDN Web文档 在JavaScript中判断一个字符串是否在Base64中

如果你需要编码一个HTML图像对象,你可以写一个简单的函数,像这样:

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  // escape data:image prefix
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  // or just return dataURL
  // return dataURL
}

通过id获取图像的Base64编码:

function getBase64ImageById(id){
  return getBase64Image(document.getElementById(id));
}

还有更多。

如果你使用Node.js,你可以这样做:

let a = Buffer.from('JavaScript').toString('base64');
console.log(a);

let b = Buffer.from(a, 'base64').toString();
console.log(b);