Home > Net >  Convert image path to base64 in typescript
Convert image path to base64 in typescript

Time:03-27

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

CodePudding user response:

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.

  • Related