I want to display base64 image for profile picture. The image is stored in database as binary data and I converted this binary data into base64 using btoa(). now I want to bind this base64 image to img src I tried many ways but it's not working, please help here is my code
profile.ts code:
profilePicture(binImage)
{
if(binImage != null)
{
var imageData = btoa(binImage);
//console.log("Base64 Image: ",imageData);
this.displayImage = imageData;
}
}
profile.html code:
<div class="profile-picture big-profile-picture" *ngIf="displayImage">
<img src="data:Image/*;base64,{{displayImage}}">
</div>
It is showing an error "sanitizing unsafe url value safevalue must use [property]=binding"
If you don't want to store the data twice, you can put the metadata string right in the html. This worked better for my scenario
<div class="profile-picture big-profile-picture">
<img src="{{'data:image/png;base64,' + imageData}}">
</div>
In your typescript file, in CameraOptions you can replace FILE_URI
by DATA_URL
like this destinationType: this.camera.DestinationType.DATA_URL
Add a sanitizer and sanitize the url before using it in template
import { DomSanitizer } from '@angular/platform-browser';
...
constructor( private sanitizer: DomSanitizer, .... ) {}
...
profilePicture(binImage)
{
if(binImage != null)
{
var imageData = btoa(binImage);
//console.log("Base64 Image: ",imageData);
this.displayImage = this.sanitizer.bypassSecurityTrustUrl("data:Image/*;base64,"+imageData);
}
}
in your template just:
<div class="profile-picture big-profile-picture" *ngIf="displayImage">
<img src="{{displayImage}}">
</div>
Add browser sanitizer and sanitize the url and rather then using src="{{your_variable}}" use [src]="your_variable". For example:
import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
@Component({
selector: 'app-image-modal',
templateUrl: './image-modal.page.html'],
})
export class ImageModalPage {
user_image: SafeResourceUrl;
constructor( private sanitizer: DomSanitizer ) { }
loadImage(){
this.user_image = this.sanitizer.bypassSecurityTrustResourceUrl(/* your base64 string in here*');
}
}
<img [src]="user_image" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With