boilerplate.js
Version:
Development Tools
47 lines (40 loc) • 1.36 kB
JavaScript
/* How To Use
b64Encode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64Encode('\n'); // "Cg=="
b64Decode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64Decode('Cg=='); // "\n"
*/
function b64Encode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64Decode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function b64FileEncode(file, cb) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
function b64ToImage(file) {
file = file.split(',')[1];
let binary = atob(file);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Uint8Array(array);
}