How to get resized image url using Firebase Resize Image extension form Reactjs app?

638 Views Asked by At

I have reactjs app and some images to show. Now I try to optimise my images. So I tried to resize and change the image to Webp format using firebase's Resize Image extension. So I got the images with name, example test_album_40x40.webp, test_album_300x300.webp. My question is that how can I get that url. When I upload image.jpeg, I got the following url return from firestore.

test_album.jpeg (original url that return from firestore when it is upload and store it in db)

https://firebasestorage.googleapis.com/v0/b/myanmargita-bf003.appspot.com/o/images/albums/test_album.jpeg?alt=media&token=edd4799b-5b23-4940-b0f8-88ce57329625

test_album_40x40.webp

https://firebasestorage.googleapis.com/v0/b/project_id.appspot.com/o/images/albums/thumbs/test_album_40x40.webp?alt=media&token=cb2b2c92-68c6-49e8-8b64-b2788b7a1396

test_album_300x300.webp

https://firebasestorage.googleapis.com/v0/b/myanmargita-bf003.appspot.com/o/images/albums/thumbs/test_album_300x200.webp?alt=media&token=cb2b2c92-68c6-49e8-8b64-b2788b7a1396

Update Event to firestore and save to db

const handleSave = async (data) => {
const file = data.album_cover;
const storageRef = ref(storage, "images/albums/" + file.name);
const  uploadTask = uploadBytesResumable(storageRef,file);
uploadTask.on(
  "state_changed",
  (snapshot) => {
    var progress = Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    setUploadProgress({ progress });
  },
  (error) => {
    throw error;
  },
  () => {
    getDownloadURL(uploadTask.snapshot.ref).then((url) => {
      data.album_cover = url;
      add_albumByArtist({
        variables:addVariable(data, auth),
        refetchQueries: [getAlbums]
      });
    }
    );
  }
);
navigate(-1);
  };
1

There are 1 best solutions below

1
Dildar Khan On

I ran into the same issue, this is how I did it. I am doing it only for 100x100 size but you can call it multiple times according to your needs.

uploadStatus.on("state_changed",(snapshot) => {
 const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
 setImageUploadProgress(progress);
 },
 (error) => {
  throw error;
 },
async () => {
 const url = await getDownloadURL(uploadStatus.snapshot.ref);
 const imagePath = uploadStatus.snapshot.ref.fullPath;
 let imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
 const extension = imageName.split(".").pop();
 const name = imageName.split(".").slice(0, -1).join(".");
 imageName = name + "_" + "100x100" + "." + extension;
 const storageRef = ref(firebaseStorage, "path_to_storage_resize_images_folder" + imageName);
 const thumbURL = await getDownloadURL(storageRef);
 setImageSource(url);
 setImageThumb(thumbURL);
});