9

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>

Check this image, it't not displaying the picture

It is showing an error "sanitizing unsafe url value safevalue must use [property]=binding"

Shreyas Pednekar
  • 1,285
  • 5
  • 31
  • 53

5 Answers5

7

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>
mike_t
  • 2,484
  • 2
  • 21
  • 39
3

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" />
ZearaeZ
  • 899
  • 8
  • 20
2

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>
2

In your typescript file, in CameraOptions you can replace FILE_URI by DATA_URL like this destinationType: this.camera.DestinationType.DATA_URL

SANA Abdoul Aziz
  • 423
  • 4
  • 14
0

Try putting a public address for the URL, in case you have a server where they are saved, you must put the public address of your server and the password where the image is saved.