【问题标题】:Resize/Compress selected image before uploading to firebase in angular在以角度上传到firebase之前调整大小/压缩所选图像
【发布时间】:2021-07-10 05:15:10
【问题描述】:

我让我的用户上传他们的个人资料图片,该图片显示为 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 ""
  }

}

我尝试了很多方法,但似乎都没有奏效,有人知道或以前做过吗?

【问题讨论】:

  • 你应该尝试使用这个:npmjs.com/package/ngx-image-compress
  • 它工作得很好,但是它将图像作为 base64 字符串返回,我需要它作为图像文件,所以我可以将它上传到 firebase,有什么想法吗?

标签: javascript html angular firebase image


【解决方案1】:

您可以使用它来将 base64 转换为文件 blob。

  const split = base64Image.split(',');
  const type = split[0].replace('data:', '').replace(';base64', '');
  const byteString = atob(split[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(arrayBuffer);
  for (let i = 0; i < byteString.length; i += 1) {
    ia[i] = byteString.charCodeAt(i);
  }
  const fileBlob = new Blob([arrayBuffer], {type}); // upload this to firebase.

【讨论】:

  • 使用 ngx-image-compress 和这个 base64 来实现 blob,谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2021-01-03
  • 2016-09-30
  • 2021-11-14
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多