React Native
launchCameraAsync
Learn to get images from camera with launchCameraAsync.
launchCameraAsync
To take a photo with the camera you call ImagePicker.launchCameraAsync. This function also returns a result object like launchImageLibraryAsync; the canceled and assets fields work the same. The only difference is that the camera opens and the user takes a photo.
Camera permission must be requested separately. On iOS camera permission is requested automatically; on Android it is recommended to request it explicitly with requestCameraPermissionsAsync. The taken photo is retrieved with result.assets[0].uri. The function takes an options object; for example { mediaTypes: ImagePicker.MediaTypeOptions.Images }.
Difference between the two selections
launchImageLibraryAsync picks from the gallery, launchCameraAsync captures with the camera. Both return the same result object; so the following steps are identical. Many apps have two buttons: 'Pick from gallery' and 'Take a photo'.
You can bind both functions to the same handleImage flow; only the call differs. Example: the gallery button is onPress={pickFromGallery}, the camera button is onPress={pickFromCamera}. Both functions return result.assets[0].uri; it is written to a shared state.
Exercise Take a photo with the camera
Complete the takePhoto function. Call const result = await ImagePicker.launchCameraAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images }). If result.canceled, return null. Otherwise return result.assets[0].uri.
Show example solution
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
if (result.canceled) return null;
return result.assets[0].uri;
Test yourself
-
Write the camera call
const result = await ImagePicker.____({ mediaTypes: ImagePicker.MediaTypeOptions.Images });
Show answer
const result = await ImagePicker.launchCameraAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images });
-
Match each function to its purpose
- launchImageLibraryAsync
- Picks from gallery
- launchCameraAsync
- Captures with camera
- requestCameraPermissionsAsync
- Camera permission
- MediaTypeOptions.Images
- Only images
-
Which function takes a photo with the camera?
const result = await ImagePicker.??()
- launchImageLibraryAsync
- launchCameraAsync
- openCamera
- pickFromGallery
Show answer
launchCameraAsync — launchCameraAsync opens the camera and takes a photo.
Next lesson: Image processing