【问题标题】:How to save picture using ionic camera preview如何使用离子相机预览保存图片
【发布时间】:2019-05-02 19:35:43
【问题描述】:

我正在使用 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}`;
  }

【问题讨论】:

    标签: angular ionic-framework ionic4


    【解决方案1】:

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

    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';
        });
      }`
    

    一旦保存在变量中,您就可以将其保存到手机中,例如使用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);
                      }
              );
    }
    
    

    【讨论】:

    • 我现在试过了,我仍然无法在图库中找到保存的图像。
    • 查看原生存储的github链接,说明卸载应用后数据会丢失。 “通过多个会话保存数据,即保存数据直到应用程序从设备中删除”。链接:“github.com/TheCocoaProject/cordova-plugin-nativestorage
    • 原生存储通常会将数据保存在手机中,直到您卸载应用程序,但不会保存在图库中。要将照片保存在图库中,请查看此 pugin base64-to-gallery
    • 是的,这行得通。谢谢你。另外你还需要手动为android申请存储权限。
    【解决方案2】:

    离子/原生 CameraPlugin .takePicture() 方法返回一个承诺。要获得值,您需要稍微更改代码。

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

    【讨论】:

    • 我已经有了价值。我需要将捕获的图像保存到我的移动设备的图库中。
    • 哦,我误解了您问题中“保存”的含义。要将图片保存在图库中,您应该查找插件 base64-to-gallery ionicframework.com/docs/native/base64-to-gallery。那里的说明应该可以帮助您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多