launchCameraAsync
- React Native course
- Advanced
- Lesson 16/83
- 5 min
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.
Practice 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.
Starter code
import * as ImagePicker from 'expo-image-picker';
export async function takePhoto() {
// take a photo with the camera and return the uri
}Sample solution
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
if (result.canceled) return null;
return result.assets[0].uri;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the camera call
const result = await ImagePicker.____({ mediaTypes: ImagePicker.MediaTypeOptions.Images });
const result = await ImagePicker.launchCameraAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images });
Explanation: launchCameraAsync opens the camera.
2 Match each function to its purpose
| Term | Meaning |
|---|---|
launchImageLibraryAsync |
Picks from gallery |
launchCameraAsync |
Captures with camera |
requestCameraPermissionsAsync |
Camera permission |
MediaTypeOptions.Images |
Only images |
3 Which function takes a photo with the camera?
const result = await ImagePicker.??()- launchImageLibraryAsync
- launchCameraAsync Correct answer
- openCamera
- pickFromGallery
Explanation: launchCameraAsync opens the camera and takes a photo.