Say I only have a URL of the image and I wanted to get the BAse64 string value of it from a cross-domain script, without using DOM or Canvas or jQuery. Is this possible?...by just using pure Javascript?
1 Answer
If the image is a cross-domain resource, you will not be able to read it unless the server serves the image with appropriate CORS headers. The browser never allows scripts to read the contents of cross-origin resources (this is the heart of the same-origin policy) unless the cross-origin server explicitly allows this with CORS.
Assuming you do have an image with appropriate CORS headers (or just a same-origin image), you can fetch the image as a Blob (using responseType) and read it as a file to get the base64-encoded data: URL:
var xhr = new XMLHttpRequest()
xhr.open("GET", "myimg.png");
xhr.responseType = "blob";
xhr.send();
xhr.addEventListener("load", function() {
var reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.addEventListener("loadend", function() {
console.log(reader.result);
});
});
btoa(…)to convert to Base64, but you still need to figure out how to get the image from a different domain.