Reputation: 469
I want to convert multiple Images simultaneously inside for loop in ionic 3
my code is:
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);
}
but not getting full base64 strings of all images.
How can i convert image url in base64 strings inside array and display all converted images in offline mode ionic 3?
please give me solution as soon as possible.
Upvotes: 2
Views: 352
Reputation: 469
solved above issue using below function,
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;
});
}
when you want converted images from array, call that function in your array as below:
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);
});
}
Upvotes: 1