❓ Get captured photo as blob
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
- [X] I am using Expo
- [X] I have read the Troubleshooting Guide
- [X] I agree to follow this project's Code of Conduct
- [X] I searched for similar questions in the issues page as well as in the discussions page and found none.
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.
https://github.com/itinance/react-native-fs/issues/417
@ericlifs could try this, I am attempting that. Will update you on the attempt.
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
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 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))
};
I don't think React Native's fetch allows you to fetch local files... 🤔
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);
}
};
https://docs.mux.com/guides/video/upload-files-directly#2-use-that-url-to-upload-in-your-client
Huh okay, maybe this does work. What exactly is the error message when you try to fetch a local file from VisionCamera?
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.
my response now looks like:
bodyUsed: false
headers: Headers {map: {…}}
ok: false
status: 0
statusText: ""
type: "default"
url: ""
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}
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?
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
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
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! :)
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],
)
@mrousavy did we ever add this feature to vision camera?
This solution worked! TLDR: Convert
react-native-vision-cameraPhotoFile to blob usingfetchand thereby convert blob to base64 usingFileReaderconst 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
Thank you for your response. I solved it in my code by doing this.
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.
Thank you for your response. I solved it in my code by doing this.
![]()
![]()
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!