Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Efficient way to convert base64 string to ArrayBuffer

Given a base64 string, what is the safest and most efficient way to create an ArrayBuffer. Specifically a typeless array buffer in pure modern JavaScript.

The first SO result is this question from 2014. The accepted answer is

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

It already assumes a type and there are comments which suggest that this is not always correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this still the best solution today? Do we have to iterate over all elements in a for loop? Is there a better and more efficient way using vanilla JS where we can pass a blob of the string?

An example problem is processing a GLTF buffer which is provided as a base64 encoded string:

let str = 'data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=';

This has two separate views of scalar (unsigned short) and vec3 (float) data, requiring further processing.

[edit]

So the most popular answer is not of use here as it creates a TypedArray but the data in the base64 string does not represent a homogenous data set.

>Solution :

Since your str is a data:uri, you might use fetch:

let str = 'data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=';

fetch(str)
  .then(r => r.blob())
  .then(b => b.arrayBuffer())
  .then(buff => console.log( new Int8Array(buff) /* just for a view purpose */ ))
  .catch(e => console.log(e))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading