Shreyas Pednekar
Shreyas Pednekar

Reputation: 1305

Ionic 3- display base64 image, sanitizing unsafe url value safevalue must use [property]=binding

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"

Upvotes: 9

Views: 18983

Answers (5)

ZearaeZ
ZearaeZ

Reputation: 905

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" />

Upvotes: 3

SANA Abdoul Aziz
SANA Abdoul Aziz

Reputation: 463

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

Upvotes: 2

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.

Upvotes: 0

Lucas Crandle
Lucas Crandle

Reputation: 182

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>

Upvotes: 2

mike_t
mike_t

Reputation: 2691

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>

Upvotes: 7

Related Questions