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?
Asked
Active
Viewed 8,478 times
1
-
1No, that's not possible, unless you're using Node.js and do an XMLHttpRequest to a server that returns the Base64, that way you would be using *only javascript*, and no DOM, Canvas or jQuery – adeneo Feb 24 '16 at 18:01
-
without using canvas or dom or jquery? I think it's not possible. why u don't use canvas? – Nasser Ghiasi Feb 24 '16 at 18:05
-
You can use [`btoa(`…`)`](https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa) to convert to Base64, but you still need to figure out how to get the image from a different domain. – Sebastian Simon Feb 24 '16 at 18:05
-
@Xufox CORS CORS CORS :P – Matías Fidemraizer Feb 24 '16 at 18:12
1 Answers
6
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);
});
});

apsillers
- 112,806
- 17
- 235
- 239