DEV Community

Joey Clapton
Joey Clapton

Posted on • Updated on

Image Upload in React Native

The ImagePicker is an Expo plugin designed to simplify the process of uploading images or capturing photos using the camera without the need to directly handle complex camera or gallery APIs.

Compatibility

The ImagePicker is compatible with the following platforms:

  • Android Device
  • Android Emulator
  • iOS Device
  • iOS Simulator
  • Web Platform

Installation

npx expo install expo-image-picker
Enter fullscreen mode Exit fullscreen mode

Configuring the plugin

To configure the plugin, we will go to the app.json file and add the following configuration:

{
  "expo": {
    "plugins": [
      [
        "expo-image-picker",
        {
          "photosPermission": "The app need accesses your photos."
        }
      ]
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

In the photosPermission property, we will set the message displayed to the user, requesting approval to access the camera feature.

Implementing Image Upload Using the Mobile Gallery

import react, { useState } from "react";
import { Button, Image, View } from "react-native";
// Let's import the library.
import * as ImagePicker from "expo-image-picker";

export default function App() {
  const [image, setImage] = useState<string>();

  const pickImage = async () => {
    // No permission is required to open the gallery.
    const result = await ImagePicker.launchImageLibraryAsync({
      // The mediaTypes property defines which type of file is allowed.
      mediaTypes: ImagePicker.MediaTypeOptions.All,

      // Quality sets the image quality and accepts values from 0 to 1.      
     // 0 represents lower quality/smaller size, and 1 represents higher quality/larger size.
      quality: 1,
    });

    console.log(result);

    // Let's receive the image if the user doesn't close the photo gallery.
    if (!result.canceled) {
      const { uri } = result.assets[0];
      setImage(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 as string }}
          style={{ width: 200, height: 200 }}
        />
      ) : null}
    </View>
  );
}
Enter fullscreen mode Exit fullscreen mode

GitHub with the complete project code: https://github.com/joeyclapton/image-picker-example

References

Top comments (0)