読者です 読者をやめる 読者になる 読者になる

DRYな備忘録

Don't Repeat Yourself.

JavaScriptでbase64文字列をUint8Arrayに変換

javascript
var uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAFCAYAAABirU3bAAAAM0lEQVQIW2M0q1r+//9/BiAAEwyMZlXLgAIQDljAtGoJggcTgKlgZGRkYDSpAKpgRCgCAC8QFZ6zMZV3AAAAAElFTkSuQmCC";
var marker = "base64,";
var index = uri.indexOf(marker) + marker.length;
var base64 = uri.substring(index);
var b64map = {
    "A":[0,0,0,0,0,0],
    "B":[0,0,0,0,0,1],
// 中略
    "8":[1,1,1,1,0,0],
    "9":[1,1,1,1,0,1],
    "+":[1,1,1,1,1,0],
    "/":[1,1,1,1,1,1],
    "=":[]
};
var pool = [];
for (var i = 0; i < base64.length; i++) {
    pool = pool.concat(b64map[base64.charAt(i)]);
}
var uint8arr = new Uint8Array(pool);
console.log(uint8arr);