STUDY/React & React Native

[리액트네이티브] 갤러리에서 사진 가져오기_📷 / expo_ImagePicker , 안드로이드

ez1n 2022. 7. 19. 05:06

 

[React Native_expo-image-picker]

 

갤러리에서 사진 가져오는 방법에 대해 알아보자

 


<STUDY>

 

1. ImagePicker 설치하기

expo install expo-image-picker

 

2. 접근 권한 허용

const [galleryPermission, setGalleryPermission] = ImagePicker.useMediaLibraryPermissions();

// 권한이 없는경우 허용 여부 요청
if (!galleryPermission?.granted) {
      const permission = setGalleryPermission();
      // 허용하지 않는 경우 종료
      if(!permission.granted) {
        return null;
      }
    };

 

   💡 useMediaLibraryPermissions : 미디어 라이브러리에 대한 액세스 권한을 확인하거나 요청한다.

 

3. 이미지 가져오기

const [image, setImage] = useState(null);
    
const PressPhotoButton = async() => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [1, 1],
    quality: 1,
  });

// 이미지가 선택된 경우 state 변경
if (!result.cancelled) {
  setImage(result.uri);
}

 

options

 

   💡 mediaTypes : 선택할 미디어 유형

      ❕ default : ImagePicker.MediaTypeOptions.Images

        All, Images, Videos 중 선택

 

   💡 allowEditing : 이미지 선택 후 편집 가능 여부 (안드로이드 : 이미지 크롭, 회전 / iOS : 이미지 크롭 가능)

      ❕ default : false

 

   💡 allowMultipleSelection : 여러 파일 선택

      ❕ default : false

 

   💡 aspect : 이미지 편집 시 가로 세로 비율 (안드로이드에서만 가능, iOS는 1:1 비율이 기본)

 

   💡 quality : [0,1] 사이의 값으로 1에 가까울수록 고품질

 

   💡 videoMaxDuration : 비디오 최대 지속 시간 제한

      ❕default : 0 (무제한)

 

❔ return value

{
  "cancelled": false,
  "height": number,
  "width": number,
  "uri": "file:///data/user/0/host.exp.exponent/cache/photo.jpg"
}

 

   💡 cancelled : 요청 취소 여부 표시 (데이터 반환시 false - 요청이 취소된 경우  true)

 

   💡 uri : 데이터 파일에 대한 uri, 미디어의 크기 지정

 

4. 이미지 보여주기

return (
  <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
    <Button title={'import images'} onPress={PressPhotoButton} />
    { image && <Image style={styles.exImage} source={{uri: image}} style={{ width: 200, height: 200 }} /> }
  </View>
	);

 


 

갤러리에 접근하여 이미지를 가져와 업로드 하는 라이브러리(ImagePicker)가 생각보다 잘 설명되어 있어서 공식 홈페이지를 참고한다면 어렵지 않게 구현할 수 있었다.

 

<자세한 내용은 expo 공식 홈페이지에서 확인할 수 있습니다.>

 

 

ImagePicker - Expo Documentation

Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.

docs.expo.dev

 


 

내가 보려고 정리하는 리액트 네이티브🔆

 

👉ez1n github 구경하기👈 

 

 

ez1n - Overview

Study -ing. ez1n has 12 repositories available. Follow their code on GitHub.

github.com