React native - Camera and image library - None work

232 Views Asked by At

I am having problems getting any kind of camera and image gallery selector working? I am running expo CLI, the latest version.

When I create a new project it does not include any IOS or ANDROID folders automatically so I have no where to put any permissions (If I have to?)

I have tried virtually every tutorial going and none work.

All I need to know is what is the easiest way to achieve this and with using what. Also if I have to add the permissions, how to do so.

I have seen lots of people having this problem but no real solution.

Thanks

1

There are 1 best solutions below

0
JulesUK On

Well thanks to Michaels help and a few hours of research, I have managed to get it working and was easier than I though and far less code than things I have tried! Only tested on IOS but can now incorporate into something like a profile page with ease. Hope it helps if anyone else has the same problem.

The full code:

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);


  const pickImage = async () => {
    
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

const openCamera = async () => {
// Ask the user for the permission to access the camera
const permissionResult = await ImagePicker.requestCameraPermissionsAsync();

if (permissionResult.granted === false) {
  alert("You've refused to allow this appp to access your camera!");
  return;
}

    let result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

console.log(result);
setImage(result.assets[0].uri);

if (!result.cancelled) {
  setPickedImagePath(result.uri);
  console.log(result.uri);
}
}

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />

      <Button title="Camera" onPress={openCamera} />
       {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>
  );
}