0

I want to get the base64 of an image with Javascript.

An answer from here, https://stackoverflow.com/a/20285053/5065874 solved part of my problem.

Basically, he implemented this function:

function toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}

And used it like this:

toDataUrl('http://example/url', function(base64Img) {
    console.log(base64Img);
});

But the problem is I don't have a url to pass to toDataUrl(url, callback), rather I have an image input tag on my HTML page:

<form id="myId">
    <input type="image" name="myImage">
</form>

So what should I pass to toDataUrl() in order for the function to work correctly?

Community
  • 1
  • 1
Abubakar Ahmad
  • 2,567
  • 1
  • 18
  • 16

1 Answers1

1

You should pass the src attribute of the input element, since it should contain the URL that it displays.

toDataUrl(document.getElementsByName('myImage')[0].src, function...)
Barmar
  • 741,623
  • 53
  • 500
  • 612