Skip to content Skip to sidebar Skip to footer

Javascript: Get Base64 String From An Image Url

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

Solution 1:

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 = newXMLHttpRequest()
xhr.open("GET", "myimg.png");
xhr.responseType = "blob";
xhr.send();
xhr.addEventListener("load", function() {
    var reader = newFileReader();
    reader.readAsDataURL(xhr.response); 
    reader.addEventListener("loadend", function() {             
        console.log(reader.result);
    });
});

Post a Comment for "Javascript: Get Base64 String From An Image Url"