xref: /expo/docs/pages/tutorial/image-picker.mdx (revision bb5069cd)
1---
2title: Use an image picker
3---
4
5import { SnackInline, Terminal } from '~/ui/components/Snippet';
6import Video from '~/components/plugins/Video';
7import { A } from '~/ui/components/Text';
8
9React Native provides built-in components that are standard building blocks used by every application, such as `<View>`, `<Text>`, and `<Pressable>`.
10We want to build a feature that isn't possible with these core components and API: selecting an image from the device's media library. For that, we will need a library.
11
12To achieve this, we'll use an Expo SDK library called <A href="/versions/latest/sdk/imagepicker" openInNewTab>`expo-image-picker`</A>.
13
14> `expo-image-picker` provides access to the system's UI to select images and videos from the phone's library or take a photo with the camera.
15
16## Step 1: Install expo-image-picker
17
18To install the library, run the following command:
19
20<Terminal cmd={['$ npx expo install expo-image-picker']} />
21
22> **Tip:** Any time we install a new library in our project, we must stop the development server by pressing <kbd>Ctrl</kbd> + <kbd>c</kbd> in the terminal and then running the installation command.
23> After the installation, we can start the development server again by running `npx expo start` from the same terminal window.
24
25## Step 2: Pick an image from the device's media library
26
27`expo-image-picker` provides the `launchImageLibraryAsync()` method that displays the system UI for choosing an image or a video from the device's media library.
28
29We can use the button with the primary theme we created in the previous chapter to pick an image from the device's media library.
30We'll create a function to launch the device's image library to implement this functionality.
31
32In **App.js**, import the `expo-image-picker` library and create a `pickImageAsync()` function inside the `App` component:
33
34{/* prettier-ignore */}
35```jsx App.js
36// ...rest of the import statements remain unchanged
37/* @info Import the ImagePicker. */ import * as ImagePicker from 'expo-image-picker'; /* @end */
38
39export default function App() {
40  const pickImageAsync = async () => {
41    /* @info Pass image picker options to launchImageLibraryAsync() */
42    let result = await ImagePicker.launchImageLibraryAsync({
43      allowsEditing: true,
44      quality: 1,
45    });
46    /* @end */
47
48    if (!result.canceled) {
49      /* @info If the image is picked, print its information in terminal window. */
50      console.log(result);
51      /* @end */
52    } else {
53      /* @info If the user does not picks an image, show an alert. */
54      alert('You did not select any image.');
55      /* @end */
56    }
57  };
58
59  // ...rest of the code remains same
60}
61```
62
63Let's learn what the above code does.
64
65- The `launchImageLibraryAsync()` receives an object in which different options are specified.
66  This object is an <A href="/versions/latest/sdk/imagepicker/#imagepickeroptions" openInNewTab>`ImagePickerOptions` object</A>.
67  We can pass the object to specify different options when invoking the method.
68- When `allowsEditing` is set to `true`, the user can crop the image during the selection process on Android and iOS but not on the web.
69
70## Step 3: Update the button component
71
72When the primary button gets pressed, we need to call the `pickImageAsync()` function.
73To call it, update the `onPress` property of the `<Button>` component in **components/Button.js**:
74
75{/* prettier-ignore */}
76```jsx Button.js
77export default function Button({ label,  theme, /* @info Pass this prop to trigger the handler method from the parent component. */ onPress/* @end */}) {
78  // ...rest of the code remains same
79  if (theme === "primary") {
80    return (
81      <View>
82        /* ...rest of the code remains same */
83        <Pressable
84          style={[styles.button, { backgroundColor: '#fff' }]}
85          /* @info */ onPress={onPress} /* @end */
86        >
87      </View>
88    );
89  }
90}
91```
92
93In **App.js**, add the `pickImageAsync()` function to the `onPress` prop on the first `<Button>`.
94
95{/* prettier-ignore */}
96```jsx App.js
97export default function App() {
98  // ...rest of the code remains same
99
100  return (
101    <View style={styles.container}>
102      /* ...rest of the code remains same */
103      <Button theme="primary" label="Choose a photo" /* @info */ onPress={pickImageAsync} /* @end */ />
104    </View>
105  );
106}
107```
108
109The `pickImageAsync()` function is responsible for invoking `ImagePicker.launchImageLibraryAsync()` and then handling the result.
110The `launchImageLibraryAsync()` method returns an object containing information about the selected image.
111
112To demonstrate what properties the `result` object contains, here is an example result object:
113
114```json
115{
116  "assets": [
117    {
118      "assetId": null,
119      "base64": null,
120      "duration": null,
121      "exif": null,
122      "height": 4800,
123      "rotation": null,
124      "type": "image",
125      "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%username%252Fsticker-smash-47-beta/ImagePicker/77c4e56f-4ccc-4c83-8634-fc376597b6fb.jpeg",
126      "width": 3200
127    }
128  ],
129  "canceled": false,
130  "cancelled": false
131}
132```
133
134## Step 4: Use the selected image
135
136The `result` object provides the `assets` array, which contains the `uri` of the selected image.
137Let's take this value from the image picker and use it to show the selected image in the app.
138
139Modify the **App.js** file in the following steps:
140
141- Declare a state variable called `selectedImage` using the <A href="https://reactjs.org/docs/hooks-state.html" openInNewTab>`useState`</A> hook from React.
142  We'll use this state variable to hold the URI of the selected image.
143- Update the `pickImageAsync()` function to save the image URI in the `selectedImage` state variable.
144- Then, pass the `selectedImage` as a prop to the `ImageViewer` component.
145
146{/* prettier-ignore */}
147```jsx App.js
148/* @info Import useState hook from React. */ import { useState } from 'react'; /* @end */
149// ...rest of the import statements remain unchanged
150
151export default function App() {
152  /* @info Create a state variable that will hold the value of selected image. */
153  const [selectedImage, setSelectedImage] = useState(null);
154  /* @end */
155
156  const pickImageAsync = async () => {
157    let result = await ImagePicker.launchImageLibraryAsync({
158      allowsEditing: true,
159      quality: 1,
160    });
161
162    if (!result.canceled) {
163      /* @info Pick the first uri from the assets array. Also, there is only one image selected at a time so you don't have to change this. */
164      setSelectedImage(result.assets[0].uri);
165      /* @end */
166    } else {
167      alert('You did not select any image.');
168    }
169  };
170
171  return (
172    <View style={styles.container}>
173      <View style={styles.imageContainer}>
174        /* @info Pass the selected image URI to the ImageViewer component. */<ImageViewer
175          placeholderImageSource={PlaceholderImage}
176          selectedImage={selectedImage}
177        />
178        /* @end */
179      </View>
180      /* ...rest of the code remains same */
181    </View>
182  );
183}
184```
185
186Now, modify the **components/ImageViewer.js** file to conditionally display the selected image in place of the placeholder image.
187We'll need to pass the `selectedImage` prop to the component.
188
189The source of the image is getting long, so let's also move it to a separate variable called `imageSource`.
190Then, pass it as the value of the `source` prop on the `<Image>` component.
191
192<SnackInline
193label="Image picker"
194templateId="tutorial/02-image-picker/App"
195dependencies={['expo-image-picker', 'expo-status-bar', '@expo/vector-icons', '@expo/vector-icons/FontAwesome']}
196files={{
197'assets/images/background-image.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/503001f14bb7b8fe48a4e318ad07e910',
198'components/ImageViewer.js': 'tutorial/02-image-picker/ImageViewer.js',
199'components/Button.js': 'tutorial/02-image-picker/Button.js'
200}}>
201
202{/* prettier-ignore */}
203```jsx
204export default function ImageViewer({ placeholderImageSource, /* @info Pass the selectedImage prop.*/selectedImage/* @end */ }) {
205  /* @info If the selected image is not null, show the image from the device, otherwise, show the placeholder image. */
206  const imageSource = selectedImage !== null
207    ? { uri: selectedImage }
208    : placeholderImageSource;
209  /* @end */
210
211  return <Image /* @info */source={imageSource}/* @end */ style={styles.image} />;
212}
213```
214
215</SnackInline>
216
217In the above snippet, the `<Image>` component uses a conditional operator to load the source of the image.
218This is because the image picked from the image picker is a <A href="https://reactnative.dev/docs/images#network-images" openInNewTab>`uri` string</A>,
219not a local asset like the placeholder image.
220
221Let's take a look at our app now:
222
223<Video file="tutorial/03-image-picker-demo.mp4" />
224
225> The images used for the demo in this tutorial were picked from [Unsplash](https://unsplash.com).
226
227## Next steps
228
229We added the functionality to pick an image from the device's media library.
230
231In the next chapter, we'll learn how to [create an emoji picker modal component](/tutorial/create-a-modal).
232