react-native-vision-camera icon indicating copy to clipboard operation
react-native-vision-camera copied to clipboard

❓ Get captured photo as blob

Open ericlifs opened this issue 4 years ago • 27 comments

Question

First thank you for this awesome library, all is working smoothly. I have a related question about the camera captured photos: is there a way of getting the photo content as a blob to easily send it to a server?

What I tried

I have tried using several approaches like doing a fetch(base64) and then a .blob() but it's not working for me. I'm not sure if someone else has this same requirement and they were able to accomplish it.

VisionCamera Version

2.11.2

Additional information

ericlifs avatar Jan 11 '22 22:01 ericlifs

I want to know too.... been stuck on that, and base64 is too large that it caused problems for uploading... I was wondering if their a more better compression method, to keep the quality decent but the file size smaller.

SeamusY avatar Jan 12 '22 01:01 SeamusY

https://github.com/itinance/react-native-fs/issues/417

@ericlifs could try this, I am attempting that. Will update you on the attempt.

SeamusY avatar Jan 13 '22 01:01 SeamusY

Hey! I decided to not expose a base64 string for takePhoto because that is insanely slow and clunky to get it transferred over the old Bridge. Instead, I am working on a way better solution: https://github.com/mrousavy/react-native-jsi-image

mrousavy avatar Jan 13 '22 09:01 mrousavy

you can use fetch to get blob with the path you get from takePhoto. const getBlob = fileUri => { return fetch(fileUri).then( response => { return response.blob(); }, error => { console.log(getBlob error, error); }, ); };

JeftaJovanovic avatar Jan 14 '22 17:01 JeftaJovanovic

@JeftaJovanovic I have tried to do something like that with a video I recorded, but every time I tried to fetch the video store on the temp folder it fails, I'm using the URI I got back from the stop recording and the video renders perfect, I need this to create a blob that I could upload to our VOD provider.

the URI that I got back is:

file:///data/user/0/com.tbitmobile.qa/cache/VisionCamera-20220329_2144017934648742044078934.mp4

and I have tried different combinations:

/data/user/0/com.tbitmobile.qa/cache/VisionCamera-20220329_2144017934648742044078934.mp4
file://data/user/0/com.tbitmobile.qa/cache/VisionCamera-20220329_2144017934648742044078934.mp4
data/user/0/com.tbitmobile.qa/cache/VisionCamera-20220329_2144017934648742044078934.mp4

none of this has worked as expected, my code

const onSubmit = async () => {
    try {
      const uri = video.path;
      console.log(uri);
      const file = await fetch(uri);
      console.log(file);
    } catch (e: any) {
      console.log(e.message);
      // Network request failed
    }
    // dispatch(uploadVideo(video.path))
  };

clovisrodriguez avatar Mar 30 '22 02:03 clovisrodriguez

I don't think React Native's fetch allows you to fetch local files... 🤔

mrousavy avatar Mar 30 '22 08:03 mrousavy

Here is what I'm trying to achieve according to one of MUX video guides,

async function uploadVideo () {
  // videoUri here is the local URI to the video file on the device
  // this can be obtained with an ImagePicker library like expo-image-picker
  const imageResponse = await fetch(videoUri)
  const blob = await imageResponse.blob()

  // Create an authenticated Mux URL
  // this request should hit your backend and return a "url" in the
  // response body
  const uploadResponse = await fetch('/backend-api')
  const uploadUrl = (await uploadResponse.json()).url

  try {
    let res = await fetch(uploadUrl, {
      method: 'PUT',
      body: blob,
      headers: { "content-type": blob.type}
    });
    console.log("Upload is complete");
  } catch(error) {
    console.error(error);
  }
};

clovisrodriguez avatar Mar 30 '22 10:03 clovisrodriguez

https://docs.mux.com/guides/video/upload-files-directly#2-use-that-url-to-upload-in-your-client

clovisrodriguez avatar Mar 30 '22 10:03 clovisrodriguez

Huh okay, maybe this does work. What exactly is the error message when you try to fetch a local file from VisionCamera?

mrousavy avatar Mar 30 '22 10:03 mrousavy

Well I tried to reproduce it today, but it worked! but I want to add my insight on what I did to solve it, from another StackOverflow thread of somebody else trying to access a resource inside the app cache it seems that didn't worked due to a lack of permissions, so I added a request for reading external storage on android, test on iOS is pending but thanks for replaying so soon.

clovisrodriguez avatar Mar 30 '22 12:03 clovisrodriguez

my response now looks like:

bodyUsed: false
headers: Headers {map: {…}}
ok: false
status: 0
statusText: ""
type: "default"
url: ""
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}

clovisrodriguez avatar Mar 30 '22 12:03 clovisrodriguez

So, what's the proposed solution @mrousavy if I want to upload the image captured via this SDK to a server that expects a JPG or PNG file?

og-abdul-mateen avatar Oct 15 '22 20:10 og-abdul-mateen

So, what's the proposed solution @mrousavy if I want to upload the image captured via this SDK to a server that expects a JPG or PNG file?

@mrousavy any help on this would be appreciated

elouisramsey avatar Oct 15 '22 22:10 elouisramsey

I strongly believe that base64-encoded blob should be added as a prop in PhotoFile. Because many times, there will be a need to upload the photo to the server.

Therefore, having a blob from the photo right away would greatly ease the uploading process.

Right now, the best solution is to use either react-native-fs or rn-fetch-blob

waleedshkt avatar Nov 07 '22 05:11 waleedshkt

I strongly believe that base64-encoded blob should be added as a prop in PhotoFile. Because many times, there will be a need to upload the photo to the server.

Therefore, having a blob from the photo right away would greatly ease the uploading process.

Great, yea, I'd be happy to review and accept a PR for this! :)

mrousavy avatar Nov 08 '22 09:11 mrousavy

This solution worked! TLDR: Convert react-native-vision-camera PhotoFile to blob using fetch and thereby convert blob to base64 using FileReader

const getBlob = useCallback((fileUri: string) => {
    return fetch(fileUri).then(
      response => {
        return response.blob()
      },
      error => {
        Logger.log(`Error in converting image to blob - ${error}`)
      },
    )
  }, [])

  const blobToBase64 = useCallback(blob => {
    try {
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      return new Promise(resolve => {
        reader.onloadend = () => {
          resolve(reader.result)
        }
      })
    } catch (err) {
      Logger.log(`Error in converting blob to base64 - ${err}`)
      throw err
    }
  }, [])

  const sendImage = useCallback(
    async (imageUri: string) => {
      try {
        const blob = await getBlob(imageUri)
        blobToBase64(blob).then(finalImage =>
        // FinalImage is the finally converted base64 string
          webViewRef?.current?.injectJavaScript(
            `window.setImageCaptured('${finalImage}')`,
          ),
        )
      } catch (err) {
        Logger.log(err)
      }
    },
    [blobToBase64, getBlob],
  )

akash-dey avatar Nov 14 '22 05:11 akash-dey

@mrousavy did we ever add this feature to vision camera?

tyhudson avatar Feb 06 '23 21:02 tyhudson

This solution worked! TLDR: Convert react-native-vision-camera PhotoFile to blob using fetch and thereby convert blob to base64 using FileReader

const getBlob = useCallback((fileUri: string) => {
    return fetch(fileUri).then(
      response => {
        return response.blob()
      },
      error => {
        Logger.log(`Error in converting image to blob - ${error}`)
      },
    )
  }, [])

  const blobToBase64 = useCallback(blob => {
    try {
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      return new Promise(resolve => {
        reader.onloadend = () => {
          resolve(reader.result)
        }
      })
    } catch (err) {
      Logger.log(`Error in converting blob to base64 - ${err}`)
      throw err
    }
  }, [])

  const sendImage = useCallback(
    async (imageUri: string) => {
      try {
        const blob = await getBlob(imageUri)
        blobToBase64(blob).then(finalImage =>
        // FinalImage is the finally converted base64 string
          webViewRef?.current?.injectJavaScript(
            `window.setImageCaptured('${finalImage}')`,
          ),
        )
      } catch (err) {
        Logger.log(err)
      }
    },
    [blobToBase64, getBlob],
  )
 const blob = await getBlob(imageUri)

Throws an error Error in converting image to blob - TypeError: Network request failed

dtembo98 avatar May 02 '23 08:05 dtembo98

Thank you for your response. I solved it in my code by doing this.

image image

I do like your solution too. I thought it would have been awesome to pass a true/false to the image capture and get that back instead of saving it.

It's all good everything is working.

tyhudson avatar May 02 '23 13:05 tyhudson

Thank you for your response. I solved it in my code by doing this.

image image

I do like your solution too. I thought it would have been awesome to pass a true/false to the image capture and get that back instead of saving it.

It's all good everything is working.

This work for me also! Thanks friend!

emadel1990 avatar May 29 '23 13:05 emadel1990