Firebase / Ionic4上传并裁剪图像到存储设备

时间:2019-08-09 11:23:53

标签: javascript firebase ionic-framework ionic4 crop

嘿,我正在尝试将裁剪的图像上传到Firebase。 我宁愿使用离子型本机“图像选择器”和“裁切”。 我真的不知道裁剪后如何上传图像,因为它只返回新图像的路径。

我已经尝试过类似的方法。这行得通,但是我无法裁剪图像。但是正如我提到的,无论如何我还是更喜欢使用本机工具。

      export interface UploadData {
        name: string;
        filepath: string;
        size: number;
      }
  uploadFile(event: FileList) {        
      // The File object
      const file = event.item(0);        
      // Validation for Images Only
      if (file.type.split('/')[0] !== 'image') {
       console.error('unsupported file');
       return;
      }        
      // The storage path
      const path = `whatever/${new Date().getTime()}_${file.name}`;        
      // File reference
      const fileRef = this.storage.ref(path);        
      // The main task
      this.task = this.storage.upload(path, file, { customMetadata });        
      this.snapshot = this.task.snapshotChanges().pipe(        
        finalize(() => {
          // Get uploaded file storage path
          this.UploadedFileURL = fileRef.getDownloadURL();
          this.UploadedFileURL.subscribe(resp => {
            this.addImagetoDB({
              name: file.name,
              filepath: resp,
              size: this.fileSize
            });
          }, error => {
            console.error(error);
          });
        }),
        tap(snap => {
            this.fileSize = snap.totalBytes;
        })
      );
    }

    addImagetoDB(image: UploadData) {
        const id = this.db.createId();

        // Set document id with value in database
        this.imageCollection.doc(id).set(image).then(resp => {
          console.log(resp);
        }).catch(error => {
          console.log('error ' + error);
        });
    }
}

这就是我想要的方式。但是我真的不知道如何在这一点上上传它。

    pickImage() {
      this.imagePicker.getPictures(this.imagePickerOptions).then((results) 
    => {
        // tslint:disable-next-line: prefer-for-of
        for (let i = 0; i < results.length; i++) {
          this.cropImage(results[i]);
        }
      }, (err) => {
        alert(err);
      });
    }     
    cropImage(imgPath) {
      this.crop.crop(imgPath, { quality: 50 })
        .then(
          newPath => {
            // ?????
          },
          error => {
            alert('Error cropping image' + error);
          }
        );
    }

对不起,我对这个东西很陌生。 感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

似乎您可以在不需要裁剪功能的情况下执行此操作。

这些是选项according to the docs

options = {
    // Android only. Max images to be selected, defaults to 15. If this is set to 1, upon
    // selection of a single image, the plugin will return it.
    maximumImagesCount: int,

    // max width and height to allow the images to be.  Will keep aspect
    // ratio no matter what.  So if both are 800, the returned image
    // will be at most 800 pixels wide and 800 pixels tall.  If the width is
    // 800 and height 0 the image will be 800 pixels wide if the source
    // is at least that wide.
    width: int,
    height: int,

    // quality of resized image, defaults to 100
    quality: int (0-100),

    // output type, defaults to FILE_URIs.
    // available options are 
    // window.imagePicker.OutputType.FILE_URI (0) or 
    // window.imagePicker.OutputType.BASE64_STRING (1)
    outputType: int
};

因此您可以使用:

options = {
    maximumImagesCount: 3,
    width: 800,
    height: 600,
    quality: 50,
    outputType: 1
};

然后可以使用以下方法从I've been researching中将图像放入Firebase存储中:

storageRef.putString("Your base64 string substring variable", 'base64');

我不确定这是否足以解决问题,但我想我还是会把我发现的内容张贴出来。

答案 1 :(得分:0)

我只是试过了,但是也没有用。我不知道为什么...

constructor(private imagePicker: ImagePicker, private crop: Crop,
    private file: File) {
      let storageDb = firebase.storage();
      this.storageRef = storageDb.ref();
  }


pickImage() {
  this.imagePicker.getPictures(this.imagePickerOptions).then((results) 
=> {
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < results.length; i++) {
      this.cropImage(results[i]);
    }
  }, (err) => {
    alert(err);
  });
}  


cropImage(imgPath) {
    this.crop.crop(imgPath, { quality: 50 })
      .then(
        newPath => {
          try {
            let n = newPath.lastIndexOf("/");
            let x = newPath.lastIndexOf("g");
            let nameFile = newPath.substring(n + 1, x + 1);
            this.file.readAsArrayBuffer(newPath, nameFile).then((res) => {
              let blob = new Blob([res], { type: "image/jpeg" });
              var uploadTask = this.storageRef.child('images/' + this.event.id).put(blob);
              uploadTask.on('state_changed', (snapshot) => {
                let url = uploadTask.snapshot.downloadURL;
                this.croppedImagepath = url;
              }, (error) => {
                alert("error: " + error);
              }, () => { 
                alert("uploaded");
                let url = uploadTask.snapshot.downloadURL;
                this.croppedImagepath = url;
              })
            })
          }
          catch (z) {
            alert('error beim erstellen des blobs' + z);
          }
        },
        error => {
          alert('Error cropping image' + error);
        }
      );
  }