Typescript将图像url转换为base64编码的字符串失败

时间:2017-08-21 08:07:03

标签: angular typescript

我想将图片转换为base 64格式,并给出其URL。

以下是我的方法,以实现这一目标:

getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

// Using the function above to do the conversion (an image to base 64 format from its URL);
this.getBase64Image('https://live.mystocks.co.ke/research/images/bamburi.jpg');

失败了。

我做错了什么,我该如何实现?

1 个答案:

答案 0 :(得分:-1)

您无法从字符串中获取图片信息,您需要先加载该图片,这样您才需要返回ObservablePromise

getBase64Image(img:HTMLImageElement) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}



getBase64ImageFromURL(url:string) {
  return Observable.create((observer:Observer<string>) => {
    let img = new Image();
    img.src = url;
    if (!img.complete) {
      img.onload = () => {
        observer.next(getBase64Image(img));
        observer.complete();
      };
      img.onerror = (err) => {
        observer.error(err);
      };
    } else {
      observer.next(getBase64Image(img));
      observer.complete();
    }
  });
}