如何使用离子相机预览保存图片

How to save picture using ionic camera preview

我正在使用 Ionic 4 开发移动应用程序。一切正常,但是当我调用函数 takePicture() 时无法保存图片。 Ionic Camera Plugin 中是否有类似 saveToPhotoAlbum 的任何参数。帮帮我。

  cameraPictureOpts: CameraPreviewPictureOptions = {
    width: window.innerWidth,
    height: window.innerHeight,
    quality: 100
  }

  takePicture() {
    let result = this.cameraPreview.takePicture(this.cameraPictureOpts);
    let picture = `data:image/jpeg;base64,${result}`;
  }

ionic/native CameraPlugin .takePicture() 方法 returns 一个承诺。要获得您需要稍微更改代码的值。

  takePicture() {
    this.cameraPreview.takePicture(this.cameraPictureOpts).then(data => {
         let picture = `data:image/jpeg;base64,` + data;
    });

  }

您可以将图像保存在局部变量中。

selectedImage: any; 

pictureOpts: CameraPreviewPictureOptions = {
    width: 400,
    height: 400,
    quality: 85
};

............


takePicture() {
    console.log('take pinture');
    // take a picture
    this.cameraPreview.takePicture(this.pictureOpts).then((imageData) => {
      this.selectedImage = 'data:image/jpeg;base64,' + imageData;
      console.log('take picture ');
      this.location.back(); // go to previous page
    }, (err) => {
      console.log(err);
      this.selectedImage = 'assets/img/test.jpg';
    });
  }`

保存在变量中后,您可以将其保存到 phone,例如使用 NativeStorage

import { NativeStorage } from '@ionic-native/native-storage/ngx';

 constructor(private storage: NativeStorage) {}

saveImage() {
    this.storage.setItem('image', {property: this.selectedImage})
              .then(
                  () => {
                    console.log('Stored image!');
                  },
                  error => {
                    console.error('Error guardando la imagen', error);
                  }
          );
}