Skip to content

Instantly share code, notes, and snippets.

@metrofun
Last active August 1, 2023 11:43
Show Gist options
  • Save metrofun/5536671 to your computer and use it in GitHub Desktop.
Save metrofun/5536671 to your computer and use it in GitHub Desktop.
Script to convert image into base64, using xhr2 without canvas. Therefore it is possible to convert images from another domains, using CORS.
function getBase64FromImage(url, onSuccess, onError) {
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", url);
xhr.onload = function () {
var base64, binary, bytes, mediaType;
bytes = new Uint8Array(xhr.response);
//NOTE String.fromCharCode.apply(String, ...
//may cause "Maximum call stack size exceeded"
binary = [].map.call(bytes, function (byte) {
return String.fromCharCode(byte);
}).join('');
mediaType = xhr.getResponseHeader('content-type');
base64 = [
'data:',
mediaType ? mediaType + ';':'',
'base64,',
btoa(binary)
].join('');
onSuccess(base64);
};
xhr.onerror = onError;
xhr.send();
}
@backspaces
Copy link

OK to use fetch instead of XHR?

@aacassandra
Copy link

not work for getting image from s3 amazon aws

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment