React Native – Hardware features (1)

How to take photo?

Use react-native-camera or react-native-image-picker

react-native-image-picker

Class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { PermissionsAndroid } from 'react-native';
import { Platform } from 'react-native';
import { launchCamera } from 'react-native-image-picker';
type TCameraImage = {
base64: string;
uri: string;
width: number;
height: number;
fileSize: number;
type: string;
fileName: string;
didCancel: any;
errorCode: string;
};
export default class Camera {
mediaType = 'photo';
IMAGE_WIDTH = 800;
IMAGE_HEIGHT = 600;
private options = {
mediaType: this.mediaType,
maxWidth: this.IMAGE_WIDTH,
maxHeight: this.IMAGE_HEIGHT,
quality: 1,
videoQuality: 'low',
durationLimit: 30, // Video max duration in seconds
saveToPhotos: true, // Image/video captured via camera will be stored in temporary folder so will be deleted any time, so don't expect it to persist. Use saveToPhotos: true (default is false) to save the file in the public photos.
};
private requestCameraPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Camera Permission',
message: 'App needs camera permission',
buttonPositive: 'OK',
}
);
// If CAMERA Permission is granted
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
} else {
return true;
}
};
requestExternalWritePermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'External Storage Write Permission',
message: 'App needs write permission',
buttonPositive: 'OK',
}
);
// If WRITE_EXTERNAL_STORAGE Permission is granted
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
}
return false;
} else {
return true;
}
};
async onCaptureImage(setImageData: (data: TCameraImage | null) => void) {
const isCameraPermitted = await this.requestCameraPermission();
const isStoragePermitted = await this.requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
launchCamera(this.options, (response: TCameraImage) => {
let validation: TCameraImage | null = null;
if (response.didCancel) {
// User cancelled camera picker
validation = null;
} else if (response.errorCode === 'camera_unavailable') {
// Camera not available on device
validation = null;
} else if (response.errorCode === 'permission') {
// Permission not satisfied
validation = null;
} else if (response.errorCode === 'others') {
// response.errorMessage
validation = null;
} else {
validation = response;
}
setImageData(validation);
});
}
}
}
import { PermissionsAndroid } from 'react-native'; import { Platform } from 'react-native'; import { launchCamera } from 'react-native-image-picker'; type TCameraImage = { base64: string; uri: string; width: number; height: number; fileSize: number; type: string; fileName: string; didCancel: any; errorCode: string; }; export default class Camera { mediaType = 'photo'; IMAGE_WIDTH = 800; IMAGE_HEIGHT = 600; private options = { mediaType: this.mediaType, maxWidth: this.IMAGE_WIDTH, maxHeight: this.IMAGE_HEIGHT, quality: 1, videoQuality: 'low', durationLimit: 30, // Video max duration in seconds saveToPhotos: true, // Image/video captured via camera will be stored in temporary folder so will be deleted any time, so don't expect it to persist. Use saveToPhotos: true (default is false) to save the file in the public photos. }; private requestCameraPermission = async () => { if (Platform.OS === 'android') { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.CAMERA, { title: 'Camera Permission', message: 'App needs camera permission', buttonPositive: 'OK', } ); // If CAMERA Permission is granted return granted === PermissionsAndroid.RESULTS.GRANTED; } catch (err) { console.warn(err); return false; } } else { return true; } }; requestExternalWritePermission = async () => { if (Platform.OS === 'android') { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, { title: 'External Storage Write Permission', message: 'App needs write permission', buttonPositive: 'OK', } ); // If WRITE_EXTERNAL_STORAGE Permission is granted return granted === PermissionsAndroid.RESULTS.GRANTED; } catch (err) { console.warn(err); } return false; } else { return true; } }; async onCaptureImage(setImageData: (data: TCameraImage | null) => void) { const isCameraPermitted = await this.requestCameraPermission(); const isStoragePermitted = await this.requestExternalWritePermission(); if (isCameraPermitted && isStoragePermitted) { launchCamera(this.options, (response: TCameraImage) => { let validation: TCameraImage | null = null; if (response.didCancel) { // User cancelled camera picker validation = null; } else if (response.errorCode === 'camera_unavailable') { // Camera not available on device validation = null; } else if (response.errorCode === 'permission') { // Permission not satisfied validation = null; } else if (response.errorCode === 'others') { // response.errorMessage validation = null; } else { validation = response; } setImageData(validation); }); } } }
import { PermissionsAndroid } from 'react-native';
import { Platform } from 'react-native';
import { launchCamera } from 'react-native-image-picker';

type TCameraImage = {
  base64: string;
  uri: string;
  width: number;
  height: number;
  fileSize: number;
  type: string;
  fileName: string;
  didCancel: any;
  errorCode: string;
};

export default class Camera {
  mediaType = 'photo';
  IMAGE_WIDTH = 800;
  IMAGE_HEIGHT = 600;

  private options = {
    mediaType: this.mediaType,
    maxWidth: this.IMAGE_WIDTH,
    maxHeight: this.IMAGE_HEIGHT,
    quality: 1,
    videoQuality: 'low',
    durationLimit: 30, // Video max duration in seconds
    saveToPhotos: true, // Image/video captured via camera will be stored in temporary folder so will be deleted any time, so don't expect it to persist. Use saveToPhotos: true (default is false) to save the file in the public photos.
  };

  private requestCameraPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: 'Camera Permission',
            message: 'App needs camera permission',
            buttonPositive: 'OK',
          }
        );
        // If CAMERA Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        return false;
      }
    } else {
      return true;
    }
  };

  requestExternalWritePermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'External Storage Write Permission',
            message: 'App needs write permission',
            buttonPositive: 'OK',
          }
        );
        // If WRITE_EXTERNAL_STORAGE Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
      }
      return false;
    } else {
      return true;
    }
  };

  async onCaptureImage(setImageData: (data: TCameraImage | null) => void) {
    const isCameraPermitted = await this.requestCameraPermission();
    const isStoragePermitted = await this.requestExternalWritePermission();
    if (isCameraPermitted && isStoragePermitted) {
      launchCamera(this.options, (response: TCameraImage) => {
        let validation: TCameraImage | null = null;
        if (response.didCancel) {
          // User cancelled camera picker
          validation = null;
        } else if (response.errorCode === 'camera_unavailable') {
          // Camera not available on device
          validation = null;
        } else if (response.errorCode === 'permission') {
          // Permission not satisfied
          validation = null;
        } else if (response.errorCode === 'others') {
          // response.errorMessage
          validation = null;
        } else {
          validation = response;
        }
        setImageData(validation);
      });
    }
  }
}

Usage

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const camera = new Camera();
interface Props {}
const Example: React.FC<Props> = () => {
const [image, setImage] = React.useState<TCameraImage | null>(null);
const onCaptureImage = async () => {
await camera.onCaptureImage(setImage);
};
return (
<Container>
<Button
title={'Camera'}
onPress={onCaptureImage}
/>
{image ? (
<PreviewImage
source={{ uri: image.uri }}
/>
) : null}
</Container>
);
};
export default Example;
const camera = new Camera(); interface Props {} const Example: React.FC<Props> = () => { const [image, setImage] = React.useState<TCameraImage | null>(null); const onCaptureImage = async () => { await camera.onCaptureImage(setImage); }; return ( <Container> <Button title={'Camera'} onPress={onCaptureImage} /> {image ? ( <PreviewImage source={{ uri: image.uri }} /> ) : null} </Container> ); }; export default Example;
const camera = new Camera();

interface Props {}

const Example: React.FC<Props> = () => {
  const [image, setImage] = React.useState<TCameraImage | null>(null);

  const onCaptureImage = async () => {
    await camera.onCaptureImage(setImage);
  };

  return (
    <Container>
        <Button
          title={'Camera'}
          onPress={onCaptureImage}
        />
        {image ? (
          <PreviewImage
            source={{ uri: image.uri }}
          />
        ) : null}
    </Container>
  );
};

export default Example;

How to browse photo library?

Class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export default class Camera {
...
const browseImage = (setImageData) => {
let options = {
mediaType: 'photo',
maxWidth: 300,
maxHeight: 550,
quality: 1,
};
launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
alert('User cancelled camera picker');
return;
} else if (response.errorCode == 'camera_unavailable') {
alert('Camera not available on device');
return;
} else if (response.errorCode == 'permission') {
alert('Permission not satisfied');
return;
} else if (response.errorCode == 'others') {
alert(response.errorMessage);
return;
}
setImageData(response);
});
};
}
export default class Camera { ... const browseImage = (setImageData) => { let options = { mediaType: 'photo', maxWidth: 300, maxHeight: 550, quality: 1, }; launchImageLibrary(options, (response) => { console.log('Response = ', response); if (response.didCancel) { alert('User cancelled camera picker'); return; } else if (response.errorCode == 'camera_unavailable') { alert('Camera not available on device'); return; } else if (response.errorCode == 'permission') { alert('Permission not satisfied'); return; } else if (response.errorCode == 'others') { alert(response.errorMessage); return; } setImageData(response); }); }; }
export default class Camera {
  ...
  const browseImage = (setImageData) => {
    let options = {
      mediaType: 'photo',
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
    };
    launchImageLibrary(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        alert('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        alert('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        alert('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        alert(response.errorMessage);
        return;
      }
      setImageData(response);
    });
  };
}

Usage

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const camera = new Camera();
interface Props {}
const Example: React.FC<Props> = () => {
const [image, setImage] = React.useState(null);
const onBrowseImage = async () => {
await camera.browseImage(setImage);
};
return (
<Container>
<Button
title={'Camera'}
onPress={onBrowseImage}
/>
{image ? (
<PreviewImage
source={{ uri: image.uri }}
/>
) : null}
</Container>
);
};
export default Example;
const camera = new Camera(); interface Props {} const Example: React.FC<Props> = () => { const [image, setImage] = React.useState(null); const onBrowseImage = async () => { await camera.browseImage(setImage); }; return ( <Container> <Button title={'Camera'} onPress={onBrowseImage} /> {image ? ( <PreviewImage source={{ uri: image.uri }} /> ) : null} </Container> ); }; export default Example;
const camera = new Camera();

interface Props {}

const Example: React.FC<Props> = () => {
  const [image, setImage] = React.useState(null);

  const onBrowseImage = async () => {
    await camera.browseImage(setImage);
  };

  return (
    <Container>
        <Button
          title={'Camera'}
          onPress={onBrowseImage}
        />
        {image ? (
          <PreviewImage
            source={{ uri: image.uri }}
          />
        ) : null}
    </Container>
  );
};

export default Example;

How to browse file?

Use react-native-document-picker

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import DocumentPicker from 'react-native-document-picker';
export default class BrowseFile {
onOpen = async () => {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
});
return res;
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
console.log('Cancelled');
} else {
console.log(err);
}
}
};
}
import DocumentPicker from 'react-native-document-picker'; export default class BrowseFile { onOpen = async () => { try { const res = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); return res; } catch (err) { if (DocumentPicker.isCancel(err)) { // User cancelled the picker, exit any dialogs or menus and move on console.log('Cancelled'); } else { console.log(err); } } }; }
import DocumentPicker from 'react-native-document-picker';

export default class BrowseFile {
  onOpen = async () => {
    try {
      const res = await DocumentPicker.pick({
        type: [DocumentPicker.types.allFiles],
      });
      return res;
    } catch (err) {
      if (DocumentPicker.isCancel(err)) {
        // User cancelled the picker, exit any dialogs or menus and move on
        console.log('Cancelled');
      } else {
        console.log(err);
      }
    }
  };
}

How to read QR code?

Use react-native-qrcode-scanner

Be the first to comment

Leave a Reply

Your email address will not be published.


*