0

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

1 回答 1

0

如果要显示 base 64 图像,则需要在模板中使用之前对 url 进行清理。

import { DomSanitizer } from '@angular/platform-browser';

...
constructor( private sanitizer: DomSanitizer, .... ) {}
...

profilePicture(binImage)
{
    if(binImage != null)
    {
        var imageData = btoa(binImage);
        //console.log("Base64 Image: ",imageData);
        this.displayImage = this.sanitizer.bypassSecurityTrustUrl("data:Image/*;base64,"+imageData);
    }
}

在您的模板中:

<div class="profile-picture big-profile-picture" *ngIf="displayImage">
    <img src="{{displayImage}}">
</div>
于 2019-04-24T10:49:19.743 回答