在Ionic 3中显示由Native Camera拍摄的FILE_URI图像

时间:2018-03-25 17:10:02

标签: ionic-framework ionic3 ionic-native

如何在Ionic 3中使用@ionic-native/camera显示用户拍摄的FILE_URI图像?

我可以使用Ionic Native的相机获取FILE_URI图片网址,结果如下:

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

但是,当我尝试通过参考视图模板中的URI将此图像显示给用户时,图像永远不会加载。

我尝试过的事情:

- 直接在视图中使用图像URI

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

- 通过在页面组件中包含DomSanitizer来限制URI:

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

由于性能阻力,我宁愿不使用base64图像。我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

从'ionic-angular'导入{normalizeURL}; 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));
   });
 }

答案 1 :(得分:0)

Hi try to use File Path ionic plugin

path = "file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg";
this.filePath.resolveNativePath(path)
   .then(filePath => console.log(filePath))
   .catch(err => console.log(err));

Please read the documentation https://ionicframework.com/docs/native/file-path/

答案 2 :(得分:-1)

您可以使用以下代码显示图像

savePhotoClick = () =>{

const options: CameraOptions = {
  quality: 70,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE
}

this.camera.getPicture(options).then((imageData) => {
  // imageData is either a base64 encoded string or a file URI
  // If it's base64 (DATA_URL):
  this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
  // Handle error
});

然后使用img标签进行显示

 <img [src]="base64Image" *ngIf="base64Image" />