1. 程式人生 > 其它 >js base64與Uint8Array互轉

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;
     }
}

寫在最後

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦: