CodeBlanks Logo Icon CodeBlanks

launchImageLibraryAsync

Learn to pick images with launchImageLibraryAsync.

launchImageLibraryAsync

To pick an image from the gallery you call ImagePicker.launchImageLibraryAsync. The function returns an object; the canceled field is true if the user canceled the selection, the assets field carries the picked images. Since assets is an array you get the first image with assets[0].

The function takes an options object; for example { mediaTypes: ImagePicker.MediaTypeOptions.Images } shows only images. You await the result object. Example: const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images }). The code waits until the user makes a selection.

The result object

The returned object has two important fields. The canceled field becomes true if the user canceled the selection; in this case assets stays empty. The assets field is an array; each element is an image object carrying fields like uri, width, height.

To get the first image you write result.assets[0]. For the cancel check you use the if (result.canceled) return; pattern. These two checks together form a safe selection flow. Trying to process the image before a selection is made raises an error; so the cancel check is mandatory.

Practice Pick an image from the gallery

Complete the pickImage function. Call const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images }). If result.canceled, return null. Otherwise return result.assets[0].uri.

Starter code

App.js
import * as ImagePicker from 'expo-image-picker';

export async function pickImage() {
  // pick an image from the gallery and return the uri
}

Sample solution

App.js
const result = await ImagePicker.launchImageLibraryAsync({
  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 result variable

Question
const ____ = await ImagePicker.launchImageLibraryAsync(options);
Answer
const result = await ImagePicker.launchImageLibraryAsync(options);

Explanation: The result variable carries the selection result.

2 Match each field to its meaning

Term Meaning
canceled Cancel state
assets Picked image array
uri Image path
assets[0] First image

3 What is done when canceled?

App.js
if (result.canceled) { ... }
  • Return early; no image Correct answer
  • Process the image
  • Close the app
  • Throw an error

Explanation: When canceled, return early; the image is not processed.

All lessons in Advanced