React Native

[React-Native] react-native-image-picker

sayhee 2022. 10. 21. 16:04
728x90

안녕하세요 세히이 입니다 ! 카메라 구현하는데 애를 많이 먹었습니다 흑

RN 카메라 Vision 카메라 Image Picker 여러가지 찾아보았는데 RN 카메라는 deprecated 되었다고 하여 쓰지 않았고

Image-Picker을 시도해보았어요

 

  • 카메라 아이콘을 누르면 모달이 뜨며 실행이 되도록 하였습니다

Image-Picker 설치
npm install --save react-native-image-picker

 

android / app / src / main / AndroidManifest.xml 접근 권한 수정

 

모달 구현 ( UploadModeModal.js )
import React from "react";
import { StyleSheet, Modal, View, Pressable, Text } from "react-native";
import Icon from "react-native-vector-icons/MaterialIcons";

function UploadModeModal({visible, onClose, onLaunchCamera, onLaunchImageLibrary}) {
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="fade"
      onRequestClose={onClose} >
      <Pressable style={styles.background} onPress={onClose}>
        <View style={styles.whiteBox}>
          <Pressable
            style={styles.actionButton}
            android_ripple={{color: "#eee"}}
            onPress={() => {
              onLaunchCamera();
              onClose();
            }} >
            <Icon name="camera-alt" color="#757575" size={24} style={styles.icon} />
            <Text style={styles.actionText}>카메라로 촬영하기</Text>
          </Pressable>
          <Pressable
            style={styles.actionButton}
            android_ripple={{color: "#eee"}}
            onPress={() => {
              onLaunchImageLibrary();
              onClose();
            }} >
            <Icon name="photo" color="#757575" size={24} style={styles.icon} />
            <Text style={styles.actionText}>사진 선택하기</Text>
          </Pressable>
        </View>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  background: {
    backgroundColor: "rgba(0,0,0,0,6)",
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  whiteBox: {
    width: 300,
    backgroundColor: "white",
    borderRadius: 4,
    elevation: 2,
  },
  actionButton: {
    padding: 16,
    flexDirection: "row",
    alignItems: "center",
  },
  icon: {
    marginRight: 8,
  },
  text: {
    fontSize: 26,
  },
});

export default UploadModeModal;

 

Import ( ImageBlob.js )
import UploadModeModal from "./UploadModeModal";
import { launchImageLibrary, launchCamera } from "react-native-image-picker";
import { PermissionsAndroid } from 'react-native';

 

카메라 & 사진 선택 구현 ( ImageBlob.js )
const imagePickerOption = {
	mediaType: "photo",
	maxWidth: 768,
	maxHeight: 768,
	includeBase64: Platform.OS === "android",
};

function ImageBlob() {

    const requestCameraPermission = async () => { 
        try {
            const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.CAMERA,
            {
              title: "App Camera Permission",
              message:"App needs access to your camera ",
              buttonNeutral: "Ask Me Later",
              buttonNegative: "Cancel",
              buttonPositive: "OK"
            }
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log("Camera & storage permission given");
          
            var options = {
              mediaType: 'photo', //to allow only photo to select ...no video
              saveToPhotos:true,  //to store captured photo via camera to photos or else it will be stored in temp folders and will get deleted on temp clear
              includeBase64:false,
            };
    
            launchCamera (options, (res) => {
              console.log('Response = ', res);
                
              if (res.didCancel) {
                console.log('User cancelled image picker');
              } else if (res.error) {
                console.log('ImagePicker Error: ', res.error);
              } else if (res.customButton) {
                console.log('User tapped custom button: ', res.customButton);
                alert(res.customButton);
              } else {
               // let source = res;
                // var resourcePath1 = source.assets[0].uri;
                const source = { uri: res.uri };
                console.log('response', JSON.stringify(res));
                //setImageSource(res.uri);
              }
            });
          } 
          else {
            console.log("Camera permission denied");
          }
        } catch (err) {
          console.warn(err);
        }
      };
  // 선택 사진 또는 촬영된 사진 정보
  const onPickImage = (res) => { 
    if (res.didCancel || !res) {
      return;
    }
    console.log("PickImage", res);
  }
  
  // 카메라 촬영
  const onLaunchCamera = () => {
    
    launchCamera(imagePickerOption, onPickImage);
  };
  
  // 갤러리에서 사진 선택
  const onLaunchImageLibrary = () => {
    launchImageLibrary(imagePickerOption, onPickImage);
  };

  // 안드로이드를 위한 모달 visible 상태값
  const [modalVisible, setModalVisible] = useState(false);
  
  // 선택 모달 오픈
  const modalOpen = () => {
    if (Platform.OS === "android") { // 안드로이드
      setModalVisible(true); // visible = true
    } else { // iOS
      
    }
  }
  
  return (
    <>
      <View>
        <Pressable onPress={modalOpen}>
          <Icon name="camera-alt" color="black" size={30} />
        </Pressable>
      </View>
      <UploadModeModal 
        visible={modalVisible} 
        onClose={() => setModalVisible(false)}
        onLaunchCamera={requestCameraPermission}
        onLaunchImageLibrary={onLaunchImageLibrary} />
    </>
  );
}

export default ImageBlob;

 

image picker를 직접 적용해 본 결과 직접 여러가지 제가 원하는 api를 쓰는 것에 있어 무리가 있는 것 같아

여러가지 api를 지원하고 있는 react-native-vision-camera를 다시 적용하여 올 예정입니다 :)