为什么我无法在阵列ion 3中获得完整的base64字符串?

时间:2018-07-30 10:48:07

标签: typescript base64 ionic3

enter image description here我想在离子3中同时在循环中转换多个图像

我的代码是:

   for (let i in serviceData) {
    // for(let i=0; i< this.adviceArray.length; i++) {
      console.log("online advices", serviceData[i]);
      this.texto = serviceData[i].texto;
      console.log("check online this.texto ", this.texto );
      this.imagen = serviceData[i].imagen;
      console.log("check online this.imagen", this.imagen);

      this.convertToDataURLviaCanvas(serviceData[i].imagen, "image/jpeg").then(base64 => {
        console.log("online base64", base64);
        this.base64Image = base64;
        console.log("online this.base64Image", this.base64Image);
        // this.adviceArrays64.push({'texto': this.texto, 'imagen': this.base64Image});
      });
      console.log("outer online this.base64Image", this.base64Image);
      this.adviceArrays64.push({'texto': this.texto, 'imagen': this.base64Image});
      console.log("online this.adviceArrays64", this.adviceArrays64);
      this.storage.set("travelTips64", this.adviceArrays64);
    }

但未获得所有图像的完整base64字符串。

如何在数组内部的base64字符串中转换图像url,并以脱机模式ionic 3显示所有转换后的图像?

请尽快给我解决方案。

1 个答案:

答案 0 :(得分:1)

使用以下功能解决了上述问题,

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

        dataURL = canvas.toDataURL();
        //callback(dataURL);
        canvas = null;
        resolve(dataURL);
    };
    img.src = url;
});

}

当您要从数组转换图像时,请按如下所示在数组中调用该函数:

let base64Image;
for (let i in serviceData) {
 this.imagen = serviceData[i].imagen;
 this.convertToDataURLviaCanvas(this.imagen, "image/jpeg").then(base64 => {
  base64Image = base64;
  this.texto = serviceData[i].texto;
  this.adviceArrays64.push({'texto': this.texto, 'imagen': base64Image});
   this.storage.set("travelTips64Image", this.adviceArrays64);
  });
}