Resize/Compress selected image before uploading to firebase in angular

Viewed 814

I let my users upload their profile image, which shows as a 150x150 pixels circle, I want the image to be resized/compress when he selects it to upload to Firebase. Here is my JavaScript to select and upload the image:

<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 ""
  }

}

I've tried many approaches, but none seems to be working, anyone got any idea or have done this before?

1 Answers

You can use this, to convert base64 to file 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.
Related