Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Convert a base64 string into a binary Uint8 Array
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
@PAEz

Thanks, you made my day.

@borismus
Owner

Glad for it!

@Muffo

Thanks for this script!

@brettz9

Small nit: your "i" needs a "var" declaration to avoid it becoming global...

@sureshbora1989

Thanks Buddy :)

@fabiosantoscode

:) nice!

@sebasao

fantastic!

@ajxs

Real nice function!
Building on your example, if you're targeting Firefox and feeling adventurous you can shorten the function down to this:

var BASE64_MARKER = ';base64,';
function convertDataURIToBinaryFF(dataURI) { 
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length; 
    var raw = window.atob(dataURI.substring(base64Index));
    return Uint8Array.from(Array.prototype.map.call(raw,function(x) { 
            return x.charCodeAt(0); 
        })); 
};

Unfortunately Uint8Array.from() isn't supported in other browsers yet. But this example might be useful someday!

@IuryAlves

Thanks! You save my week =D

@hungconcon

I love you so much, same me a week, wanna invite you for a cup of coffee!

@ICEDLEE337

Is there any way to make this work with IE 9?

@olegrise

Nice! Worked like a charm for me. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.