[SOLVED] Convert image path to base64 in typescript

Issue

i have path of the image and want to covert it to base64 type like this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg…

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();
}
  
toDataUrl("imagepath", function(myBase64) {
  console.log(myBase64); // myBase64 is the base64 string
});

output – data:text/html;base64,PCFET0NUWVBFIGh…. my output came like this but the data type is text/html but i want the data type to be image/jpeg

output screenshot – output

Solution

Your code works as is. When I run that with an imgur url, I get:

"data:image/png;base64,iVBORw0KGgoAAAAN..."

See playground and click "run" to execute the sc ript.

Which means that your server must be returning text/html rather than an image. So make your are calling the correct URL and that the server is returning what it’s supposed to because javascript here works just fine.

Answered By – Alex Wayne

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *