关于react native vision摄像头拍照并保存

cnh2zyt3  于 2022-11-17  发布在  React
关注(0)|答案(2)|浏览(131)

我是react native的新手。如果我想在点击按钮后在桌面上有一张图片,我需要做什么?只是简单地想拍一张照片。我昨天试过这样做,并成功了,但我现在不能这样做。

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
正如你在这里所看到的,框架现在并不重要。

rggaifut

rggaifut1#

您可以使用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}`);
uplii1fm

uplii1fm2#

import {Camera} from 'react-native-vision-camera';

请使用const camera = useRef<Camera>(null)而不是const camera = useRef(null)

相关问题