Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 673
thedbogh Avatar asked Nov 30 '22 14:11

thedbogh


2 Answers

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

like image 169
Richang Sharma Avatar answered Dec 04 '22 08:12

Richang Sharma


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;
like image 25
Jason Spence Avatar answered Dec 04 '22 06:12

Jason Spence