【问题标题】:Firebase/Ionic4 upload and Crop Images to storageFirebase/Ionic4 上传和裁剪图像到存储
【发布时间】:2019-12-17 03:14:31
【问题描述】:

嘿,我正在尝试将裁剪后的图像上传到 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);
          }
        );
    }

对不起,我对这些东西很陌生。 谢谢你的帮助:)

【问题讨论】:

  • 似乎没有人会回答这个问题。昨晚我试着写点东西,但是......我真的不知道答案:P 我昨天和今天都试图为你解决这个问题,但没有成功。猜猜你在学习的时候需要从更简单的东西开始。我找不到任何解释这个特定任务链的教程。
  • 嗯,好吧,那太伤心了:(但感谢您的尝试
  • 是的,一般情况下事情进展得很快,所以如果你没有尽早得到答案,它可能不会到来。不过,我一直在进一步研究。

标签: javascript firebase ionic-framework ionic4 crop


【解决方案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');

我不确定这是否足以让您解决问题,但我想我还是会发布我发现的内容。

【讨论】:

  • 你对这样的事情有什么看法?它也适用于ios吗?如果我使用裁剪功能:stackoverflow.com/questions/42156069/…
  • 我认为你不需要那个。 outputType: 1 将为您提供一组 base64 编码数据。如果您将 url 发布到裁剪库,那么我可以查看它支持哪些选项?
  • ionicframework.com/docs/native/crop 好像不是很详细
  • 好吧,是的,如果你想使用它,那么你不能让选择器为你加载图像,因为作物不接受 base64。因此,您需要弄清楚如何将文件从路径上传到 Firebase 存储。如果我找到任何东西,我会告诉你的。
  • 好像you need a File or Blob,也就是说你需要convert a path to a file使用file/cordova插件。
【解决方案2】:

我刚试过这个,但它也不起作用。我不知道为什么...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2015-08-10
    • 2011-07-12
    • 2019-02-03
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多