Ionic 2: Base64 encoded images rendering with unsafe: prefix

If you are binding base64 encoded images to your views and sometimes they're screwing up, this little method 'fixes' it.

The problem:

For some reason, some of my base64 encoded images are not being treated as 'safe' in Ionic 2 and Angular 2. I don't know why. So they're being rendered like this:

<img src="unsafe:data:image/jpeg;base64,/9.....

See the 'unsafe:' prefix?

Fuck that.

1) In your class, import the 'DomSanitizer' e.g.:

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

  templateUrl: 'somePage.html'
export class SomePage {

    public _DomSanitizer: DomSanitizer,
  ) {

2) Then in your template where the image is broken, use it like this:

<img [src]="_DomSanitizer.bypassSecurityTrustUrl(imgSrcProperty)"/>

Where imgSrcProperty is the offending image base64 encoded.


I say 'fixes' because it's a hack. You're essentially disabling the security around that property in order to make it work. However, if you're certain that the image is coming from a trusted source, or you're in charge of the source, then don't worry I guess.

StackOverflow question here.