Ionic 4-本机相机插件问题

时间:2019-04-04 18:10:54

标签: android cordova cordova-plugins ionic4 ionic-native

我已经使用Ionic4开发了一个android应用程序。 Ionic Native Camera插件遇到一些问题。以下是我的代码。下面是我面临的问题。如果我使用的相机插件版本为"@ionic-native/camera": "^5.3.0",

问题

  1. 画廊没有开放
  2. 捕获的图像没有返回。
  3. 拍照后应用程序崩溃

html

<img [src]="studentImage!==null ? studentImage: 'assets/icon/ic_avatar.png'" class="add-picture" (click)="addImage()">

.ts

 public addImage() {
    this.genericServices.presentActionSheet(this.openGallery, this.openCamera);
  }

private openCamera = () => {
    this.studentImage = this.genericServices.selectPicture('camera');
    console.log('Captured Image:=>' + this.studentImage);
  }
  private openGallery() {
    this.studentImage = this.genericServices.selectPicture('gallery');
  }

服务

  public async selectPicture(source) {
    let base64Image = null;
    const cameraOptions: CameraOptions = {
      quality: 75,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.PNG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: source === 'camera' ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY,
      correctOrientation: true
    };

    await this.camera.getPicture(cameraOptions).then((imageData) => {
      console.log('Returned Image=>' + base64Image);
      return base64Image = 'data:image/jpeg;base64,' + imageData;
    }).catch(() => {
    });
  }

1 个答案:

答案 0 :(得分:0)

很难说出您的问题是什么。我可能会编写略有不同的代码,如下所示:

async selectImage(){

const actionSheet = await this.actionCtrl.create({
    header: "Select Image source",
    buttons: [{
            text: 'Load from Library',
            handler: () => {
              this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
            }
        },
        {
            text: 'Use Camera',
            handler: () => {
                this.takePicture(this.camera.PictureSourceType.CAMERA);
            }
        },
        {
            text: 'Cancel',
            role: 'cancel'
        }
    ]
});
await actionSheet.present(); 
}

然后在takePicture()方法中确定destinationType应该是什么,默认值为FILE_URI(1)。

 takePicture(sourceType: PictureSourceType) {
    var options: CameraOptions = {
        quality: 80,
        sourceType: sourceType,
        saveToPhotoAlbum: false,
        correctOrientation: true,
        destinationType: 1,
        targetWidth: 1240,
        targetHeight: 768,
    };
    this.camera.getPicture(options)
    .then((imageData) => {
      // do something with the imageData, should be able to bind it to a variable and 
      // show it in your html file. You might need to fix file path, 
      // remember to import private win: any = window, and use it like this.

      this.imagePreview = this.win.Ionic.WebView.convertFileSrc(imageData);

    }).catch((err) => {
      console.warn("takePicture Error: " + err);
    });
  }

这应该工作正常...我刚刚测试了它。但是正如我所说,您的设置可能有几处错误。希望它能以某种方式有所帮助...否则会造成麻烦,我会很乐意为您查看代码。