In this blog, we are going to create a simple image picker with expo-image-picker.
First of all install expo-image-picker.
By running this command in your terminal:
expo install expo-image-picker
Now import this components inside your app.
import * as ImagePicker from 'expo-image-picker';
We will also use Image component from react-native to display selected Image:
import { Image } from 'react-native';
Than we will create a function inside our component:
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
// more code ...
}
To View this image inside our component we will use react state:
const [images,setImages] = React.useState(null);
And than we will update pickImage function:
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
// New code block
if (!result.cancelled) {
setImage(result.uri);
}
};
We can display image like this:
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
To open image picker we will call pickerImage function on Button press:
<Button title="Pick an image from camera roll" onPress={pickImage} />
This is how our app looks like at the end:
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function ImagePickerExample() {
const [image, setImage] = useState(null);
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
}
I Hope this article helps you.
Happy coding:)
Top comments (0)