在上传到firebase之前调整/压缩选定图像的大小

yrdbyhpb  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(203)

我让我的用户上传他们的个人资料图像,它显示为一个150x150像素的圆圈,我希望当他选择上传到firebase时,图像能够被调整大小/压缩。下面是我选择并上传图像的javascript:

<label for="upload-picture" class="upload-picture button-small">Upload Picture</label>
<input id="upload-picture" type="file" style="display: none" (change)="uploadPicture($event)" accept=".jpeg,.jpg,.png,.svg">
import { Component, OnInit } from '@angular/core';
import { AngularFirestoreDocument } from '@angular/fire/firestore';
import { FbUser } from 'src/app/common/fb-user';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-profile-info',
  templateUrl: './profile-info.component.html',
  styleUrls: ['./profile-info.component.scss']
})
export class ProfileInfoComponent implements OnInit {

  constructor(
    public _auth: AuthService,
  ) { }

  ngOnInit(): void {

  }

  currentImageUrl: string = "";

  async uploadPicture(e: any) {
    const file = e.target.files[0]
    //Here i want to reduce image size 
    //(image shows as a 150x150 in the DOM so i dont need it to be bigger than that since firebase has a 5GB limit of free storage)
    const filePath = this._auth.userData.uid
    const task = await this.uploadImage(filePath, file)

    if (task) {
      this.currentImageUrl = await this._auth._afstg.ref(task).getDownloadURL().toPromise();

      const userRef: AngularFirestoreDocument<any> = this._auth._afs.doc(`users/${filePath}`);
      const userData: FbUser = {
        uid: filePath,
        email: this._auth.userData.email,
        displayName: this._auth.userData.displayName,
        photoURL: this.currentImageUrl,
        emailVerified: this._auth.userData.emailVerified
      }
      userRef.set(userData, {
        merge: true
      })
      alert("Image Uploaded Successfully")
      window.location.reload()
    } else {
      alert("Error when uploading image, try again")
    }
  }

  async uploadImage(uid: string, file: any): Promise<string> {
    const fileRef = this._auth._afstg.ref(uid).child("profile-picture");

    // Upload file in reference
    if (!!file) {
      const result = await fileRef.put(file);

      return result.ref.fullPath;
    }
    return ""
  }

}

我尝试过很多方法,但似乎都不管用,有人知道或者以前做过吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题