从Ionic 2中的照片库中选择时不显示照片

时间:2017-08-06 16:57:53

标签: android ionic-framework camera ionic2

我在Ionic 2中使用Camera插件上传照片。我正在Android设备上运行该应用。 Carema捕获显示在应用程序中,但从Gallery中选择时,不会显示照片。

以下方法用于Camera和Gallary:

  private openCamera(){
    var options: CameraOptions = {
      sourceType: this.camera.PictureSourceType.CAMERA,
      destinationType: this.camera.DestinationType.DATA_URL,
      allowEdit: true,
      saveToPhotoAlbum: true
    };

    this.camera.getPicture(options).then((imageData) => {
      this.cameraData = 'data:image/jpeg;base64,' + imageData;
      this.photoTaken = true;
      this.photoSelected = false;
 let base64Image = 'data:image/jpeg;base64,' + imageData;
  }, (err) => {
 // Handle error
});

  }

    private selectFromGallery() {
    var options = {
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI
    };
    this.camera.getPicture(options).then((imageData) => {
      this.cameraUrl = imageData;
      this.photoSelected = true;
      this.photoTaken = false;
    }, (err) => {
      // Handle error
    });
  }

以下是在HTML页面中显示的代码:

<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">

1 个答案:

答案 0 :(得分:0)

当您从库中选择时,您需要使用文件插件来获取本地文件系统URL。

安装:

$ ionic cordova plugin add cordova-plugin-file
$ npm install --save @ionic-native/file

导入:

import { File } from '@ionic-native/file';

并在您的代码中:

constructor( private file: File, .... ) {}

.....


const options: CameraOptions = {
  destinationType: this.camera.DestinationType.FILE_URI,
  sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}

this.camera.getPicture(options).then((imageURI) => {
  this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {

    this.cameraUrl = fileEntry.nativeURL;
    this.photoSelected = true;
    this.photoTaken = false;
  });
}, (err) => {
  // Handle error
});

修改

您可能需要清理img src的值:

<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)"   />

功能:

import { DomSanitizer } from '@angular/platform-browser';

....

constructor( private sanitizer: DomSanitizer, .... ) {}

....

sanitizeUrl(url) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
}