Displaying a FILE_URI image taken by Native Camera in Ionic 3

caitlin picture caitlin · Mar 25, 2018 · Viewed 10.4k times · Source

How do you display a FILE_URI image taken by the user using @ionic-native/camera in Ionic 3?

I can use Ionic Native's Camera to get a FILE_URI image URL, with a result like this:

file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg

However, When I try to display this image back to the user by referring to the URI in my view template, the image never loads.

Things I've tried:

-Using the image URI directly in the view

<img src="{{profile.image}}">    // Never loads

-Sanitizing the URI by including DomSanitizer in the page component:

<img [src]="domSanitizer.bypassSecurityTrustUrl(profile.image)">    // Never loads

I would rather not use a base64 image because of the performance drag. What am I doing wrong here?

Answer

Manoj Bhardwaj picture Manoj Bhardwaj · Mar 26, 2018

import { normalizeURL } from 'ionic-angular'; ionic3 <img> tag src

<img *ngIf="base64Image" src="{{base64Image}}"/> 

 openCamera(pictureSourceType: any) {
  let options: CameraOptions = {
   quality: 95,
   destinationType: this.camera.DestinationType.FILE_URI,
   sourceType: pictureSourceType,
   encodingType: this.camera.EncodingType.PNG,
   targetWidth: 400,
   targetHeight: 400,
   saveToPhotoAlbum: true,
   correctOrientation: true
 };
 this.camera.getPicture(options).then(imageData => {
  if (this.platform.is('ios')) {
      this.base64Image = normalizeURL(imageData);
      // Alternatively if the problem only occurs in ios and normalizeURL 
      // doesn't work for you then you can also use:
      // this.base64Image= imageData.replace(/^file:\/\//, '');
  }
  else {
      this.base64Image= "data:image/jpeg;base64," + imageData;
  }
 }, error => {
     console.log('ERROR -> ' + JSON.stringify(error));
   });
 }