js base64与Uint8Array互转
1.情景展示
base64如何转Uint8Array?
Uint8Array如何转成base64?
2.base64转Uint8Array
/**
* base64字符串转为uint8array数组
*/
const base64ToUint8Array = function(base64String) {
try{
let padding = '='.repeat((4 - base64String.length % 4) % 4);
let base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
let rawData = atob(base64);
let outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
catch(e) {
throw e;
}
}
3.Uint8Array转base64
/**
* uint8array数组转为base64字符串
*/
const uint8arrayToBase64 = function(u8Arr) {
try{
let CHUNK_SIZE = 0x8000; //arbitrary number
let index = 0;
let length = u8Arr.length;
let result = '';
let slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
// web image base64图片格式: "data:image/png;base64," + b64encoded;
// return "data:image/png;base64," + btoa(result);
return btoa(result);
}
catch(e) {
throw e;
}
}
本文来自博客园,作者:Marydon,转载请注明原文链接:https://www.cnblogs.com/Marydon20170307/p/16968194.html