在 Angular 中将图像 url 转换为 base64

问题描述:

我正在努力尝试将给定的图像 url 转换为 base64...在我的情况下,我有一个带有图像路径的字符串

I am struggling trying to convert a given image url to base64... in my case i have a String with the image's path

var imgUrl = `../../../../../assets/logoEmpresas/${empresa.logoUrl}`

如何将给定的图片网址直接转换为 base64 格式?...我试过这篇文章.

how can i convert the given image url in a base64 directly?... i tried this post.

将图像转换为 angular 2 中的 base64

但是这篇文章是从表单中获取图像...我该如何调整它?

but this post is getting the image from a form... how can i adapt it?

你可以用这个来获取base64图像

You can use this to get base64 image

async function 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);
  })
}

那就这样称呼吧

getBase64ImageFromUrl('your url')
    .then(result => testImage.src = result)
    .catch(err => console.error(err));