Home > Software engineering >  How can I resize an image before to upload to firebase?
How can I resize an image before to upload to firebase?

Time:09-21

I have files to upload to firebase from reactjs. The files are likes this: they have a lot of properties:

[File {path: 'image1.jpg', index: 0, fName: 'imageBall1.jpg', type: 'jpg', …},
 File {path: 'image2.jpg', index: 1, fName: 'imageBall2.jpg', type: 'jpg', …}]

I want to resize before to upload, so I did this code

export const resizeFile = async imageFiles => {
  return await imageFiles.map(async file => {
    const a =  await new Promise((resolve) => {
    Resizer.imageFileResizer(
      file,
      300,
      300,
      "JPEG",
      100,
      0,
      (uri) => {
        resolve(uri);
      },
      "base64"
    );
    });
    console.log('file', file, a)
    return a
  })
}

But I am getting this result:

Blob data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHRyWFlaAAABZAAAABRnWFlaAAABeAAAABRiWFlaAAABjAAAABRyVFJDAAABoAAAAChnVFJDAAABoAAAAChiVFJDAAAB

That I can not upload to firebase, how can I resize an image to upload to firebase? or should I convert that binary to image again?

I would rather upload in image not in binary

CodePudding user response:

You can remove data:image/jpeg;base64, in your base64 string. And then you use .putString(image, 'base64', {contentType:'image/jpg'}); to upload into firebase.

Make sure that you have {contentType:'image/jpg'} to let firebase know file type.

You can find out more here. https://firebase.google.com/docs/storage/web/upload-files#upload_from_a_string

CodePudding user response:

What you have is a base-64 encoded binary representation of the jpg. This is usually fine to send to the server. Image files, like all files, are just binary files with certain filenames or special headers that signal how consuming applications should use them. Plenty of applications, including web browsers can consume base-64 encoded images. See here for an example of how to render a base-64 string as an image. I believe if you store a new file in firebase where the contents is your base-64 string, you will be able to use the resulting file like any other image. Firebase even has an example of uploading a base-64 string in their documentation.

  • Related