JavaScriptでUint8Array ⇄ Base64文字列の相互変換
Uint8Array → Base64
code:js
function uint8ArrayToBase64(uint8Array) {
return btoa(String.fromCharCode(...uint8Array));
}
Base64 → Uint8Array
code:js
function base64ToUint8Array(base64Str) {
const raw = atob(base64Str);
return Uint8Array.from(Array.prototype.map.call(raw, (x) => {
return x.charCodeAt(0);
}));
}
使用例
code:js
const arr = new Uint8Array(1, 2, 3); const base64 = uint8ArrayToBase64(arr);
base64ToUint8Array(base64);
関連: