BASE64 to image angular 2 BASE64 to image angular 2 angular angular

BASE64 to image angular 2


I feel like this thread lacks concrete examples which made me have some difficulties:

Import DomSanitizer:

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

define in constructor:

constructor(private _sanitizer: DomSanitizer) { }

Sanitize the Base64 string you want to pass as your image source (use trustResourceUrl):

this.imagePath = this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,'                  + toReturnImage.base64string);

Bind to html:

<img [src]="imagePath">


Solution: Just use 'data:image/jpg;base64' into your image tag like this

<img src="{{'data:image/jpg;base64,' + imagePath}}" />


You can try to use _sanitizer.bypassSecurityTrustUrl to tell angular src value is safe. Take a look at this class from angular:

class DomSanitizationService {    sanitize(context: SecurityContext, value: any) : string    bypassSecurityTrustHtml(value: string) : SafeHtml    bypassSecurityTrustStyle(value: string) : SafeStyle    bypassSecurityTrustScript(value: string) : SafeScript    bypassSecurityTrustUrl(value: string) : SafeUrl    bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl}

and be low an example for safe html:

export class AppComponent  {    private _htmlProperty: string = '<input type="text" name="name">';    public get htmlProperty() : SafeHtml {       return this._sanitizer.bypassSecurityTrustHtml(this._htmlProperty);    }    constructor(private _sanitizer: DomSanitizationService){}}