0

I have a function that converts a image to base64 and returns the value.

In .ts file:--

async getBase64ImageFromUrl(imageUrl) {
  const proxyurl = "https://cors-anywhere.herokuapp.com/";
  var res = await fetch(proxyurl+imageUrl);
  var blob = await res.blob();

  return new Promise((resolve, reject) => {
    var reader  = new FileReader();
    reader.addEventListener("load", function () {
      // console.log(reader.result); /// getting the base64 image URL here.
      resolve(reader.result);
      return;
    }, false);

    reader.onerror = () => {
      return reject(this);
    };
  
    reader.readAsDataURL(blob);
  })
}

I wanted to get the value in in the HTML, I know I am doing something wrong

<img class="w-100" [src]="getBase64ImageFromUrl('https://dam.dev.catalog.1worldsync.com/im/img/GCP-5129882489061376')"/>

I know I am doing it wrong, wanted to know the right way to do this.

  • I think you can use async pipe here to get an actual value [src]="getBase64ImageFromUrl('https://dam.dev.catalog.1worldsync.com/im/img/GCP-5129882489061376') | async" – Nifiro Dec 06 '20 at 19:05

1 Answers1

-1

It's not Angular specific.

In general, you need to prepend the base64 string with data:image/png;base64 if it was a png image.

<img src="data:[<mediatype>][;base64],<data>" />

Example:

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Check these for more info:

Mahmoud
  • 9,729
  • 1
  • 36
  • 47
  • I know how to add base64 url to src, but I am already the value in that format in the line console.log(reader.result); but due to promise it is not rendering. I need help in the Angular part. – TRIKONINFOSYSTEMS Dec 06 '20 at 17:36
  • @TRIKONINFOSYSTEMS can you please try removing the `return` from inside the promise? – Mahmoud Dec 06 '20 at 19:56