Convert base64 string to ArrayBuffer
Try this:
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;
}
Efficient way to convert base64 string to ArrayBuffer
Since your str
is a data:uri
, you might use fetch
:
let str = 'data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=';
fetch(str)
.then(b => b.arrayBuffer())
.then(buff => console.log( new Int8Array(buff) /* just for a view purpose */ ))
.catch(e => console.log(e))
Converting between strings and ArrayBuffers
Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.
TextEncoder
The TextEncoder
represents:
The
TextEncoder
interface represents an encoder for a specific method,
that is a specific character encoding, likeutf-8
,An encoder takes a stream of code points as input andiso-8859-2
,koi8
,
cp1261
,gbk
, ...
emits a stream of bytes.
Change note since the above was written: (ibid.)
Note: Firefox, Chrome and Opera used to have support for encoding
types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and
gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no
other encoding types are available other than utf-8, in order to match
the spec.*
*) Updated specs (W3) and here (whatwg).
After creating an instance of the TextEncoder
it will take a string and encode it using a given encoding parameter:
if (!("TextEncoder" in window)) alert("Sorry, this browser does not support TextEncoder...");
var enc = new TextEncoder(); // always utf-8console.log(enc.encode("This is a string converted to a Uint8Array"));
Creating a BLOB from a Base64 string in JavaScript
The atob
function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.
const byteCharacters = atob(b64Data);
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt
method for each character in the string.
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array
constructor.
const byteArray = new Uint8Array(byteNumbers);
This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob
constructor.
const blob = new Blob([byteArray], {type: contentType});
The code above works. However the performance can be improved a little by processing the byteCharacters
in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
Full Example:
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); }
const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); }
const blob = new Blob(byteArrays, {type: contentType}); return blob;}
const contentType = 'image/png';const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
const blob = b64toBlob(b64Data, contentType);const blobUrl = URL.createObjectURL(blob);
const img = document.createElement('img');img.src = blobUrl;document.body.appendChild(img);
Proper way to encode arrayBuffer to Base64 and vice-versa
Your base 64String contains data:[<mediatype>][;base64],<data>
at the begining so you need to get everything else after that.
You can try this var myBase64 = str.split('base64,')[1];
and then do your checks.
You can read more here:
Related Topics
Differencebetween String Primitives and String Objects in JavaScript
How to Refresh a Page Using JavaScript
Node.Js on Multi-Core MAChines
Callback After All Asynchronous Foreach Callbacks Are Completed
Does React Keep the Order for State Updates
Check Whether a String Matches a Regex in Js
Check If a Variable Is of Function Type
How to Get JSON from Url in JavaScript
How to Run Gulp Tasks Sequentially One After the Other
Primitive Value VS Reference Value
How to Add New Array Elements at the Beginning of an Array in JavaScript
How to Set the Value Property in Angularjs' Ng-Options
Most Efficient Way to Convert an HTMLcollection to an Array
Detecting Arrow Key Presses in JavaScript
When to Use Es6 Class Based React Components VS. Functional Es6 React Components