Last active
August 1, 2023 11:43
-
-
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.
This file contains 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
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(); | |
} |
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
OK to use fetch instead of XHR?