How can I display image encoded in base64 format in Angular 6?

33,969

Solution 1

You don't use "this" to refer the variables defined in the component "ts" file. Remove "this" may solve your problem.

Please Review this stackbliz Fiddle. Look inside the app component to see the implementation.

StackBlitz

Solution 2

This is what worked for me when working with base64 images.

HTML:

<img [src]="currVerifiedLoanOfficerPhoto">

Component:

this.currVerifiedLoanOfficerPhoto = 'data:image/jpg;base64,' + (this.sanitizer.bypassSecurityTrustResourceUrl(item) as any).changingThisBreaksApplicationSecurity;

Solution 3

You don't use this in html templates in Angular. All the variables/member methods are resolved on class by default. Access the variables directly as follows:

<img [src]="hello" />
Share:
33,969
thedbogh
Author by

thedbogh

Updated on August 24, 2020

Comments

  • thedbogh
    thedbogh over 3 years

    I struggle with a problem associated with Angular 6 and displaying image encoded in base64 format. Any ideas why code shown below doesn't display image?

    html:

    <tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
    <img src="{{this.hello}}" />
    

    ts:

    this.hello = "data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."
    

    While code shown below works properly and displays picture?

    html:

    <tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
    <!--<img src="data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."/>
    

    this.hello is assigned in the constructor just for test purpose. I create it in this way this.hello = 'data:image/png;base64, ' + this.UploaderService.imageRecognitionRowsData[0].toString() My main goal is to display imageRecognitionRowsData in this loop <tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">. So for first iteration I would display image imageRecognitionRowsData[0] then during next iteration image imageRecognitionRowsData[1] etc. The length of this.UploaderService.tableImageRecognition.dataRows is always the same as this.UploaderService.imageRecognitionRowsData When I add <p>{{this.hello}}</p> I get the same string in html. I have no idea what is wrong. I tried also with this.hello2 = this.sanitizer.bypassSecurityTrustResourceUrl(this.hello);, this.hello2 = this.sanitizer.bypassSecurityTrustUrl(this.hello);, <img [src]="this.hello" /> etc. but nothing works. Any ideas how to solve this?