function base64ToArrayBuffer(base64) {
    var binaryString = atob(base64);
    var bytes = new Uint8Array(binaryString.length);
    for (var i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}
Answer from Goran.it on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › fromBase64
Uint8Array.fromBase64() - JavaScript - MDN Web Docs
The Uint8Array.fromBase64() static method creates a new Uint8Array object from a base64-encoded string. This method should be preferred over Window.atob() because it results in a byte array, which is easier to work with than a string containing raw bytes, unless your decoded binary data is ...
Top answer
1 of 3
7

You can use XMLHttpRequest to do the dirty work for you:

var url = document.createElement("canvas").toDataURL(); // some data-uri

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
  // result = ArrayBuffer, from here assign a view to it
  if (xhr.status === 200) console.log(new Uint8Array(xhr.response));
};
xhr.send();

It's a little more code than using atob() but all conversion happens internally. It's async too which can help with larger Data-URIs.

In newer browsers (which supports it) you can instead use fetch():

// note: atm not all browsers support these features.
fetch(document.createElement("canvas").toDataURL())  // pass in some data-uri
  .then(function(response) {return response.arrayBuffer()})
  .then(function(buffer) {
    console.log(new Uint8Array(buffer));
  });

2 of 3
6

You can try with the following;

function test(base64StringFromURL)
{
   var parts = base64StringFromURL.split(";base64,");
   var contentType = parts[0].replace("data:", "");
   var base64 = parts[1];
   var byteArray = base64ToByteArray(base64);
   ..
}

function base64ToByteArray(base64String) {
        try {            
            var sliceSize = 1024;
            var byteCharacters = atob(base64String);
            var bytesLength = byteCharacters.length;
            var slicesCount = Math.ceil(bytesLength / sliceSize);
            var byteArrays = new Array(slicesCount);

            for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
                var begin = sliceIndex * sliceSize;
                var end = Math.min(begin + sliceSize, bytesLength);

                var bytes = new Array(end - begin);
                for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }
                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }
            return byteArrays;
        } catch (e) {
            console.log("Couldn't convert to byte array: " + e);
            return undefined;
        }
    }
🌐
Backendless
support.backendless.com › javascript
Decoding base64 to byte array in javascript - JavaScript - Backendless Support
June 14, 2020 - Hello everyone , I want your help in my issue , I want to decode my base64 string in backendless using javascript then save it in files but I did not find any solution . This is my code please help. const data=window.a…
🌐
IQCode
iqcode.com › code › javascript › convert-base64-string-to-byte-array-javascript
convert base64 string to byte array javascript Code Example
November 4, 2021 - Try this: function _base64ToArrayBuffer(base64) { var binary_string = window.atob(base64); var len = binary_string.length; var ...
🌐
GitHub
gist.github.com › borismus › 1032746
Convert a base64 string into a binary Uint8 Array · GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/borismus/1032746.js&quot;&gt;&lt;/script&gt; Save borismus/1032746 to your computer and use it in GitHub Desktop. Download ZIP · Convert a base64 string into a binary Uint8 Array · Raw · gistfile1.js ·
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › convert-base64-string-to-arraybuffer-in-javascript
Convert base64 String to ArrayBuffer In JavaScript - GeeksforGeeks
August 5, 2025 - The atob() function decodes a Base64-encoded string into a binary string. The Uint8Array constructor can then be used to convert this binary string into an ArrayBuffer.
Find elsewhere
🌐
Webdevtutor
webdevtutor.net › blog › javascript-base64-to-byte-array
Converting Base64 to Byte Array in JavaScript: A Step-by-Step Guide
To convert a Base64-encoded string to a byte array in JavaScript, you can use the Buffer class from the buffer module.
🌐
npm
npmjs.com › package › base64-js
base64-js - npm
November 11, 2020 - Get supported base64-js with the Tidelift Subscription · base64js has three exposed functions, byteLength, toByteArray and fromByteArray, which both take a single argument. byteLength - Takes a base64 string and returns length of byte array · ...
      » npm install base64-js
    
Published: Nov 11, 2020
Version: 1.5.1
🌐
npm
npmjs.com › package › byte-base64
byte-base64 - npm
August 18, 2020 - base64ToBytes(str: string): Uint8Array - Decodes a base64-encoded string to a Uint8Array of bytes. If str is not a valid base64-encoded string, throws new Error("Unable to parse base64 string."). base64encode(str: string, encoder: { encode: (str: string) => Uint8Array | number[] } = new TextEncoder()) ...
      » npm install byte-base64
    
Published: Aug 18, 2020
Version: 1.1.0
Top answer
1 of 1
2

The problem seem originated from this line:

byte[] picture = Convert.FromBase64String(base64img);

If the base64img contains some header like data:image/png;base64, then Convert.FromBase64String() fails because the string is not fully formatted in Base64 format. Consider using string.Split() before converting from string parameter to remove corresponding Base64 header:

[HttpPost]
public ActionResult LoadImage(Car car, string base64img)
{
    // split the header and content, separated by comma
    var base64arr = base64img.Split(',');
    byte[] picture = Convert.FromBase64String(base64arr[1]);

    // do something with the image

    return View();
}

If the content string contains characters other than ASCII or trailing padding ones, you should remove them like this:

string base64str = base64arr[1];
string processed = base64str.Replace('_', '/').Replace('-', '+');

switch (base64str.Length % 4) 
{
    case 2: 
       processed += "=="; 
       break;
    case 3: 
       processed += "="; 
       break;
}

byte[] picture = Convert.FromBase64String(processed);

Also consider using FormData object when passing image formatted with Base64 string:

$('#modalWindow').on('click', '#send', function () {
    var file = $('#autoPicture').attr('src');

    // note: if you send other form data, use 'serializeArray()' or 'serialize()'

    var formData = new FormData();
    // append other form contents here
    formData.append("base64img", file);

    $.ajax({
        type: "POST",
        url: "/Home/LoadImage",
        data: formData,
        success: function (data) {
            alert('Привет');
        },
        error: function (error) {
            alert(error.responseText);
        }
    });
});

Note:

The equals sign like = or == at the end of Base64 encoded string serves as trailing padding characters and not all Base64 encoded strings ended with them. You can see the reason behind padding here.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › setFromBase64
Uint8Array.prototype.setFromBase64() - JavaScript | MDN
The setFromBase64() method of Uint8Array instances populates this Uint8Array object with bytes from a base64-encoded string, returning an object indicating how many bytes were read and written. This method is most suitable for populating a pre-allocated array buffer.
🌐
GitHub
gist.github.com › llzes › 24fe0a9b3d786d48f2b3932a633d5b2b
Byte to Base64 implementation in JavaScript · GitHub
base64ToByte.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters · Show hidden characters · Raw · byteToBase64.js ·
🌐
Grafana
community.grafana.com › grafana k6 › oss support
Base64 encode ArrayBuffer - OSS Support - Grafana Labs Community Forums
December 7, 2020 - I have a set of bytes in an ArrayBuffer. I need to base64 encode this in k6. How do I accomplish this? In node.js it is data.toString(‘base64’) in browsers the btoa() function seems to be the way to go. Neither of these works in k6, or I did not manage to get them to work.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Window › btoa
Window: btoa() method - Web APIs - MDN Web Docs - Mozilla
js · function base64ToBytes(base64) { const binString = atob(base64); return Uint8Array.from(binString, (m) => m.codePointAt(0)); } function bytesToBase64(bytes) { const binString = Array.from(bytes, (byte) => String.fromCodePoint(byte), ).join(""); return btoa(binString); } // Usage ...