22

I am trying to get a blob response from a request, and then generate a URL from that blob and set this URL as an image's source.

But the image is not loading.

This is my HTML:

<img src="{{previewSignsrc}}" alt="Sign Thumbnail">

And this is my .ts file:

this.signModalDataService.getPreviewSignature({'name': this.SignatureName, 'font_type': 0});
    this.signModalDataService.previewSignature
      .subscribe((res) => {
        console.log(res);
        let blob = new Blob([res['_body']], {type: 'image/png'});
        this.previewSignsrc = URL.createObjectURL(blob);
        this.showPreviewSign = true;
      });

I used same method to set url for ng2-pdfviewer and it worked fine.

Matt C
  • 4,250
  • 5
  • 24
  • 43
Shoaib Iqbal
  • 2,070
  • 4
  • 22
  • 45

4 Answers4

43

You can dislay image like this code

this.config.getData()
          .subscribe((blob : any) => {
            let objectURL = URL.createObjectURL(blob);       
            this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);

          });

If your data is base64 display like this

 this.config.getData()
      .subscribe((baseImage : any) => {
        let objectURL = 'data:image/jpeg;base64,' + baseImage.image;
         this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);

      });

Demo https://stackblitz.com/edit/display-image-from-api

Hien Nguyen
  • 23,011
  • 7
  • 48
  • 55
3

You can use new FileReader(); I tried so much codes and that's the only one that worked for me.

  var reader = new FileReader ();
 reader.readAsDataURL(response) <= from inner . subscribe
  reader.onload = (_event) => {
  this.retrieveURL = reader.result;
 }

 .html
 [src]="retrieve URL" 

Bear with me I typed from my cellphone

That's all no need to use sanitizers, hope it helps somebody out there, ooh I am using Angular8

3

As was metioned earlier by Memo 313 MediaSA, FileReader works.

 const reader = new FileReader();
 reader.readAsDataURL(data); //FileStream response from .NET core backend
 reader.onload = _event => {
     url = reader.result; //url declared earlier
     image.nativeElement.src = url; //image declared earlier
 };
1

If you use JsonConvert from a .Net API to return an object in which one of the fields is the image byte[] it will convert it to a base64 string. Then you don't need anything special when calling the api or displaying the image.