Ionic 2:将URL转换为base 64图像

时间:2017-08-21 12:53:03

标签: angular typescript ionic-framework ionic2

我有图片网址,例如:https://lh3.googleusercontent.com/-lLC-FsscD40/AAAAAAAAAAI/AAAAAAAAAAA/AMp5VUoSrLythVKtt5Skm9zIUg4uyxnNCw/s48-c-mo/photo.jpg

需要将网址转换为基础64图片,我的代码无效,请帮助:

convertToDataURLviaCanvas(url){
    return new Promise( (resolve, reject) => {

        let img = new Image();
        img.crossOrigin = 'Anonymous';
        img.src = url;

        var canvas = <HTMLCanvasElement>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/jpeg");
        resolve(dataURL);

    });
}

3 个答案:

答案 0 :(得分:4)

以下是获取图像的base64数据的方法:

  ngOnInit() {
    let imageUrl = 'https://lh3.googleusercontent.com/-lLC-FsscD40/AAAAAAAAAAI/AAAAAAAAAAA/AMp5VUoSrLythVKtt5Skm9zIUg4uyxnNCw/s48-c-mo/photo.jpg';

    this.getBase64ImageFromURL(imageUrl).subscribe(base64data => {
      console.log(base64data);
      this.base64Image = 'data:image/jpg;base64,'+base64data;
    });
  }

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

  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,/, "");
  }

stackblitz的工作链接:DEMO

答案 1 :(得分:2)

这项工作对我来说

   convertToDataURLviaCanvas(url, outputFormat){
    return new Promise((resolve, reject) => {
    img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = () => {
      let canvas = <HTMLCanvasElement> document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        dataURL;
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      dataURL = canvas.toDataURL(outputFormat);
      resolve(dataURL);
      canvas = null;
    };
    img.src = url;
  });
}

简单的电话

convertToDataURLviaCanvas(base64, "image/jpeg").then(base64 => console.log(base64))

答案 2 :(得分:0)

问题在于标题,我添加了htaccess:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"