1

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?

4
  • 1
    No, 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 Commented Feb 24, 2016 at 18:01
  • without using canvas or dom or jquery? I think it's not possible. why u don't use canvas? Commented Feb 24, 2016 at 18:05
  • You can use btoa() to convert to Base64, but you still need to figure out how to get the image from a different domain. Commented Feb 24, 2016 at 18:05
  • @Xufox CORS CORS CORS :P Commented Feb 24, 2016 at 18:12

1 Answer 1

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);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.