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;
}
}
写在最后
哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!