I'm trying to convert images comes from Firebase storage to base64 string to use it on offline mode with my angular 7/ionic 4 app! ( I'm using angularfire2 )
But I got an error that said
Access to image at 'https://firebasestorage.googleapis.com/v0/b/*************************.jpg?alt=media&token=' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the >requested resource.
I have searched a lot and most of what I found is creating a firebase.json
file and allow cross but I don't know how to do this with angular
or another is set img.crossOrigin="anonymous"
which is already I did but still the problem/error there!!
Code for 2 functions resposibe to convert image url to base64
getBase64ImageFromURL(url: string) {
return Observable.create((observer: Observer<string>) => {
// create an image object
let img = new Image();
img.crossOrigin = "anonymous";
img.src = url;
if (!img.complete) {
// This will call another method that will create image from url
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) {
// We create a HTML canvas object that will create a 2d image
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
// This will draw image
ctx.drawImage(img, 0, 0);
// Convert the drawn image to Data URL
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}