react-native-image-picker launchCamera in not working in android
Asked Answered
A

5

5

I'm using "react-native-image-picker": "^3.0.1" in react native for capture image. but I got error while opening the camera in android 9.

I got error :

{"errorCode": "others", "errorMessage": "This library does not require Manifest.permission.CAMERA, if you add this permission in manifest then you have to obtain the same."}

here is my code

ImagePicker.launchCamera(
          {
            includeBase64: false,
            mediaType: 'photo',
            quality: 0.8,
          },
          async (response) => {
            if (response.didCancel) {
              console.log('User cancelled image picker');
            } else if (response.error) {
              console.log('ImagePicker Error: ', response.error);
            } else {
              
            }
          },
        );
Ancier answered 18/12, 2020 at 12:9 Comment(2)
remove ``` Manifest.permission.CAMERA``` permission as noted in the error msg if it's set in manifestBunt
I've already tried it, but still getting this issueAncier
A
23

Before capturing image, ask camera permission to user. In Android above marshmallow version you should ask Run Time permission as well which are called dangerous permission.

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 permission given");
    } else {
      console.log("Camera permission denied");
    }
  } catch (err) {
    console.warn(err);
  }
};

And then if permission granted then inside if call

ImagePicker.launchCamera
Ai answered 18/12, 2020 at 12:18 Comment(1)
This worked for me, first request permission with PermissionsAndroid, and after launchCameraPteropod
P
2
We need to add run time permissions for the react-native-image-picker . We also need to add seperate permission request for camera and external storage as.please check out below code worked for me .

  const grantedcamera = 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"
        }
      );
      const grantedstorage = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: "App Camera Permission",
          message:"App needs access to your camera ",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK"
        }
      );
      if (grantedcamera === PermissionsAndroid.RESULTS.GRANTED && grantedstorage ===  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(source.uri);
           
            
          }
        });


      } else {
        console.log("Camera permission denied");
      }
Potash answered 18/10, 2021 at 7:49 Comment(0)
U
1

this helps me

add option to android\app\src\main\AndroidManifest.xml -> section application -> param android:requestLegacyExternalStorage="true"

android\app\src\main\AndroidManifest.xml

...
    <application
      ...
      android:requestLegacyExternalStorage="true"
      ...>
Uppercase answered 17/2, 2021 at 8:51 Comment(0)
A
0

Fix the problem with this:

  • Add await to function launchCamera
  • Add includeBase64: false
  • Add parameter saveToPhotos: true
  • Add mediaType: 'photo'

{ includeBase64: false, saveToPhotos: true, mediaType: 'photo', quality: 0.5, }

 await launchCamera(
  {
    includeBase64: false,
    saveToPhotos:true,
    mediaType: 'photo',
    quality: 0.5,
  },
  (resp) => {
    try {
      if (resp.didCancel) {
        return;
      }

      if (!resp.assets) {
        return;
      }

      const assets = resp.assets[0];
      const uri = assets.uri;

      if (uri) {
        const filename = `/${documento.code}.jpg`;
        saveFileStorage(
          readFileImagePath + phoneStorageDir + filename,
          uri,
          documento,
        );
      } else {
        console.log('No hay una imagen valida');
      }
      console.log(uri);

    } catch (error) {
      console.log(error)
    }
  },
);
Amianthus answered 20/8, 2023 at 2:41 Comment(0)
D
0
import { launchCamera, launchImageLibrary, ImagePickerResponse } from 'react-native-image-picker';

const DP: React.FC = () => {
    const [gallery, setGallery] = useState<string>('https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png');

 
    const toggleComponent = () => {
      Alert.alert('Choose Option', 'Select your profile', [
          {
              text: 'Open Camera',
              onPress: () => openCamera(),
          },
          {
              text: 'Open Gallery',
              onPress: () => openGallery(),
          },
          { text: 'Cancel' },
      ]);
  };

    const openGallery = async () => {
        try {
            const result: ImagePickerResponse = await launchImageLibrary({ mediaType: 'photo', quality: 0 });
            console.log({ result });
        } catch (error) {
            console.error('Error opening gallery:', error);
        }
    };

    const openCamera = async () => {
        try {
            const result: ImagePickerResponse = await launchCamera({ mediaType: 'photo', quality: 0 });
            console.log({ result });
        } catch (error) {
            console.error('Error opening camera:', error);
        }
    };


    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 permission granted");
                toggleComponent(); // Call openCamera if permission is granted
            } else {
                console.log("Camera permission denied");
            }
        } catch (err) {
            console.warn(err);
        }
    };

    return (
        <View style={{ backgroundColor: "red", borderRadius: 40,  width: 80,
        height: 80, }}>
            <View>
                <Image
                    style={{ height: 82, width: 82, borderRadius: 50 }}
                    source={{ uri: gallery }}
                    resizeMode='cover'
                />
            </View>
            <TouchableOpacity onPress={requestCameraPermission} style={{marginTop: -20,
        paddingLeft: 60}}>
                <Entypo name="camera" size={15} color="black" />
            </TouchableOpacity>
        </View>
    );
};
Dezhnev answered 15/5 at 12:52 Comment(1)
While this code snippet may be the solution, including an explanation would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. See How do I write a good answer?. Thanks!Grillwork

© 2022 - 2024 — McMap. All rights reserved.