2

I am facing a problem and I need to convert some image, which comes from back as url and convert to base64. For example, how this image url

https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528__340.jpg

can be converted in the base64.

I know that there are image encoder web sites, like

https://www.base64-image.de/

but I need to do it dynamically in my code.

Giannis
  • 1,790
  • 1
  • 11
  • 29
  • Does this answer your question? [Converting an image to base64 in angular 2](https://stackoverflow.com/questions/42482951/converting-an-image-to-base64-in-angular-2) – ruth Sep 03 '20 at 09:59
  • No Sir.I tried all solutions but wihout access –  Sep 03 '20 at 10:16

2 Answers2

1

This worked for me:

TS FILE
base64ImageString;

async getBase64ImageFromUrl(imageUrl) {
    var res = await fetch(imageUrl);
    var blob = await res.blob();
    return new Promise((resolve, reject) => {
      var reader  = new FileReader();
      reader.addEventListener("load", function () {
          resolve(reader.result);
      }, false);
      reader.onerror = () => {
        return reject(this);
      };
      reader.readAsDataURL(blob);
    })
  }


ngOnInit() {
   this.getBase64ImageFromUrl(this.userData.organization_logo).then(base64 => {
      this.base64ImageString = base64;
    })
}

HTML

  <img src='{{ base64ImageString }}' class="logo" />
0

you can do like this, and maybe you need to resolve the origin cross if the img url is not the same origin

const image = new Image();
image.onload = function(){
  const width = image.width;
  const height = image.height;

  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(image, 0, 0);
  const base64 = canvas.toDataURL({format: "png"})
  console.log(base64);
}
  
image.src = 'https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528__340.jpg';
Ten
  • 26
  • 3