skip to Main Content

I am new in react native. What do I need to do if I want to have a picture on the desktop after I click on the button? Just simply want to take a picture. I have tried to do so and succeed yesterday but I can’t do that now.

function Cam() {
  const [hasPermission, setHasPermission] = React.useState(false);
  const isFocused = useIsFocused()
  const devices = useCameraDevices()
  const device = devices.back
  const camera = useRef(null)
  const takePhotoOptions = {
    qualityPrioritization: 'speed',
    flash: 'off'
  };
  React.useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      setHasPermission(status === 'authorized');
    })();
  }, []);
  const takePhoto = async () => {
    try {
      //Error Handle better
      if (camera.current == null) throw new Error('Camera Ref is Null');
      console.log('Photo taking ....');
      const photo = await camera.current.takePhoto(takePhotoOptions);
      console.log(photo.path)
    } catch (error) {
      console.log(error);
    }
  };




  function renderCamera() {
    if (device == null) {
      return (
        <View>
          <Text style={{ color: '#fff' }}>Loading</Text>
        </View>
      )
    }
    else {
      return (
        <View style={{ flex: 1 }}>
          {device != null &&
            hasPermission && (
              <>
                <Camera
                  ref={camera}
                  style={StyleSheet.absoluteFill}
                  device={device}
                  isActive={isFocused}
                  photo={true}
                />
                  <Text> Too much code, I delete something here </Text>
              </>
            )}
        </View>
      )
    }


  }
  return (
    <View style={{ flex: 1 }}>
      {renderCamera()}
    </View>
  );
}


export default Cam;

enter image description here

as you can see here, the frame is not important for now.

2

Answers


  1. You can use react-native-fs

                // Create pictureDirectory if it does not exist
                await RNFS.mkdir(pictureDirectory);
                // Move picture to pictureDirectory
                const filename = R.last(data.path.split('/'))!;
    
                await RNFS.moveFile(data.path, `${pictureDirectory}/${filename}`);
    
    Login or Signup to reply.
  2. import {Camera} from 'react-native-vision-camera';
    

    instead of using const camera = useRef(null) use const camera = useRef<Camera>(null)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search