티스토리 뷰

 react-native-image-picker은 React Native 애플리케이션에서 사용자의 디바이스 갤러리나 카메라를 통해 이미지나 비디오를 선택할 수 있게 해주는 라이브러리이다.

 

이 라이브러리를 사용하면 사용자가 디바이스에서 미디어를 쉽게 선택하고, 앱 내에서 이를 활용할 수 있게 된다.

 

react-native-image-picker는 iOS와 Android 플랫폼 모두를 지원하며, 다양한 커스터마이징 옵션을 제공한다.

 

설치는 뭐, 동일하다.

yarn add react-native-image-picker

npm install react-native-image-picker

 

이후에는 카메라 접근 권한을 위한 권한 설정을 해줘야 한다.

 

- 권한 설정

◎Android(android/app/src/main/AndroidManifest.xml)

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- to be added -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
   (...)
</manifest>

 

◎iOS(ios/PublicGallery<닉네임>/Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  (...)
  <key>NSPhotoLibraryUsageDescription</key>
  <string>${PRODUCT_NAME) would like access to your photo gallery</string>
  <key>NSCameraUsageDescription</key>
  <string>${PRODUCT_NAME) would like to use your camera</string>
  <key>NSPhotoLibraryAddUsageDescription</key>
  <string>${PRODUCT_NAME) would like to save photos to your photo gallery</string>
</dict>
</plist>

- 기본 사용 예제

아래는 react-native-image-picker를 사용하여 사용자가 디바이스의 카메라를 통해 사진을 찍거나 갤러리에서 사진을 선택할 수 있는 기본적인 예제 코드이다.

 

import React from 'react';
import {Button, Image, View} from 'react-native';
import ImagePicker from 'react-native-image-picker';

const App = () => {
  const [response, setResponse] = React.useState(null);

  const handleChoosePhoto = () => {
    const options = {
      noData: true,
    };

    ImagePicker.launchImageLibrary(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setResponse(response);
      }
    });
  };

  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      {response && (
        <Image
          source={{uri: response.uri}}
          style={{width: 300, height: 300}}
        />
      )}
      <Button title="Choose Photo" onPress={handleChoosePhoto} />
    </View>
  );
};

export default App;

 

이 코드는 사용자에게 갤러리에서 사진을 선택하도록 요청하고, 선택된 이미지를 앱에서 보여주는 기본적인 흐름을 구현한다. launchImageLibrary 함수를 호출하여 갤러리를 열고, 사용자가 이미지를 선택하면 그 이미지의 uri를 사용하여 Image 컴포넌트에 표시된다.

 

또한 아래와 같이 launchCamera 라이브러리를 사용하여 카메라에 접근할 수도 있다.

import React from 'react';
import {Button, Image, View} from 'react-native';
import ImagePicker from 'react-native-image-picker';

const App = () => {
  const [response, setResponse] = React.useState(null);

  const handleTakePhoto = () => {
    const options = {
      saveToPhotos: true, // 촬영한 사진을 디바이스의 갤러리에 저장
      mediaType: 'photo', // 'photo', 'video', 또는 'mixed' 중 선택 가능
    };

    ImagePicker.launchCamera(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled camera picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setResponse(response);
      }
    });
  };

  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      {response && (
        <Image
          source={{uri: response.uri}}
          style={{width: 300, height: 300}}
        />
      )}
      <Button title="Take Photo" onPress={handleTakePhoto} />
    </View>
  );
};

export default App;

 

react-native-image-picker는 다양한 옵션과 메소드를 제공하므로, 사용자의 요구에 맞게 라이브러리를 더 세밀하게 조정할 수 있다. 예를 들어, 이미지 품질을 조절하거나, 비디오를 선택하도록 설정할 수도 있다.

 

더 자세한 내용은 Docs를 확인하자.

'Mobile > react-native' 카테고리의 다른 글

[react-native] react-native-splash-screen  (0) 2024.02.13
[react-native] EventEmitter  (0) 2024.02.13
[react-native] React.forwardRef()  (0) 2024.02.10
[react-native] datetimepicker & modal  (0) 2024.02.10
[react-native] useMemo  (0) 2024.02.09
Comments