Skip to content

Instantly share code, notes, and snippets.

@metrofun
Last active August 1, 2023 11:43
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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();
}
@rashidabbas7865
Copy link

Great. Working as I wanted. Thank you for the script.

@francas
Copy link

francas commented Sep 15, 2020

Didn't work for me, still getting CORS related warnings.

@rashidabbas7865
Copy link

Didn't work for me, still getting CORS related warnings.

Can you try this code into you localhost? May be you are executing this code directly in some html file. You should run it using some server like apache etc.

@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