0

I am trying to bind a byte array to an image tag in angular. I know the byte array is correct, because I can download it and view it from my API.

I created an image like this:

<img [src]="src" />

and then in my code, I sanitized the byte array like this:

this.src = this.sanitizer.bypassSecurityTrustResourceUrl(`data:image/svg+xml,${this.location.qrCode}`);

in my console I can see this:

enter image description here

But the image isn't displaying. What am I doing wrong?


I have tried a few other things:

const reader = new FileReader();
reader.onload = (e) => (this.src = this.sanitizer.bypassSecurityTrustResourceUrl(e.target.result.toString()));
reader.readAsDataURL(new Blob([this.location.qrCode]));

and

this.src = this.sanitizer.bypassSecurityTrustResourceUrl(`data:image/svg+xml;base64,${this.test}`);

and

this.src= btoa(this.location.qrCode);

and

    const reader = new FileReader();
    reader.onload = (e) => (this.src = e.target.result);
    reader.readAsDataURL(new Blob([this.location.qrCode]));

None of them worked :(

r3plica
  • 13,017
  • 23
  • 128
  • 290

2 Answers2

0

I did some research and it turns out that my API base 64 encodes the byte array which is why it wasn't working. I simply decoded it with this:

this.svgData = atob(this.location.qrCode);

and then was able to safely render the html:

this.svg = this.sanitizer.bypassSecurityTrustHtml(this.svgData);

Which I could use in my template like this:

<div [innerHtml]="svg"></div>
r3plica
  • 13,017
  • 23
  • 128
  • 290
0

Do not encode it to base64 if the image is a svg with xml. Use base64 for images format like jpg.

Just add data:image/svg+xml, to the beggining of the image string.

In .ts:

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

this.src = this.sanitizer.bypassSecurityTrustHtml('data:image/svg+xml,' + this.location.qrCode);

In .html

<div [innerHtml]="src"></div>
A.Casanova
  • 555
  • 4
  • 16