Convert Figma logo to code with AI

teslamotors logoreact-native-camera-kit

A high performance, easy to use, rock solid camera library for React Native apps.

2,588
612
2,588
108

Top Related Projects

A Camera component for React Native. Also supports barcode scanning!

📸 A powerful, high-performance React Native Camera library.

An unified permissions API for React Native on iOS, Android and Windows.

:sunrise_over_mountains: A React Native module that allows you to use native UI to select media from the device library or directly from the camera.

Quick Overview

React Native Camera Kit is a comprehensive, high-performance camera module for React Native applications. It provides a unified API for camera functionality across iOS and Android platforms, offering features like photo capture, barcode scanning, and face detection.

Pros

  • Cross-platform compatibility with a unified API for iOS and Android
  • High performance and optimized for mobile devices
  • Rich feature set including photo capture, barcode scanning, and face detection
  • Active development and community support

Cons

  • Learning curve for developers new to camera integration in React Native
  • Some advanced features may require platform-specific code
  • Potential compatibility issues with certain React Native versions
  • Limited documentation for some advanced use cases

Code Examples

  1. Basic camera setup:
import { CameraScreen } from 'react-native-camera-kit';

const CameraComponent = () => (
  <CameraScreen
    actions={{ rightButtonText: 'Done', leftButtonText: 'Cancel' }}
    onBottomButtonPressed={(event) => console.log(event)}
    flashImages={{
      on: require('../images/flashOn.png'),
      off: require('../images/flashOff.png'),
      auto: require('../images/flashAuto.png')
    }}
    cameraFlipImage={require('../images/cameraFlipIcon.png')}
    captureButtonImage={require('../images/cameraButton.png')}
  />
);
  1. Capturing a photo:
import { Camera } from 'react-native-camera-kit';

const CapturePhoto = async () => {
  const image = await this.camera.capture();
  console.log(image.uri);
};

<Camera
  ref={ref => this.camera = ref}
  style={{flex: 1}}
  cameraType="back"
  flashMode="auto"
/>
  1. Scanning barcodes:
import { CameraScreen } from 'react-native-camera-kit';

const BarcodeScannerComponent = () => (
  <CameraScreen
    scanBarcode={true}
    onReadCode={(event) => console.log(event.nativeEvent.codeStringValue)}
    showFrame={true}
    laserColor="red"
    frameColor="white"
  />
);

Getting Started

  1. Install the package:

    npm install react-native-camera-kit
    
  2. For iOS, add camera usage description to Info.plist:

    <key>NSCameraUsageDescription</key>
    <string>Your message to user when the camera is accessed for the first time</string>
    
  3. For Android, add camera permission to AndroidManifest.xml:

    <uses-permission android:name="android.permission.CAMERA" />
    
  4. Import and use the component in your React Native app:

    import { CameraScreen } from 'react-native-camera-kit';
    
    const App = () => (
      <CameraScreen
        actions={{ rightButtonText: 'Done', leftButtonText: 'Cancel' }}
        onBottomButtonPressed={(event) => console.log(event)}
      />
    );
    

Competitor Comparisons

A Camera component for React Native. Also supports barcode scanning!

Pros of react-native-camera

  • More comprehensive feature set, including face detection and text recognition
  • Larger community and more frequent updates
  • Better documentation and examples

Cons of react-native-camera

  • Larger package size and potentially higher resource usage
  • More complex setup process
  • May have more dependencies

Code Comparison

react-native-camera:

import { RNCamera } from 'react-native-camera';

<RNCamera
  ref={ref => {
    this.camera = ref;
  }}
  style={styles.preview}
  type={RNCamera.Constants.Type.back}
  flashMode={RNCamera.Constants.FlashMode.on}
  androidCameraPermissionOptions={{
    title: 'Permission to use camera',
    message: 'We need your permission to use your camera',
    buttonPositive: 'Ok',
    buttonNegative: 'Cancel',
  }}
/>

react-native-camera-kit:

import { CameraKitCamera } from 'react-native-camera-kit';

<CameraKitCamera
  ref={cam => this.camera = cam}
  style={{flex: 1}}
  cameraOptions={{
    flashMode: 'auto',
    focusMode: 'on',
    zoomMode: 'on'
  }}
/>

Both libraries offer similar basic functionality, but react-native-camera provides more advanced features and configuration options out of the box. react-native-camera-kit has a simpler API and may be easier to integrate for basic camera functionality. The choice between the two depends on the specific requirements of your project and the level of camera control and features needed.

📸 A powerful, high-performance React Native Camera library.

Pros of Vision Camera

  • More advanced features like frame processors and QR code scanning
  • Better performance and lower resource usage
  • More active development and community support

Cons of Vision Camera

  • Steeper learning curve due to more complex API
  • May be overkill for simple camera use cases
  • Requires more setup and configuration

Code Comparison

Vision Camera:

const devices = await Camera.getAvailableCameraDevices()
const device = devices.find(d => d.position === 'back')

<Camera
  style={StyleSheet.absoluteFill}
  device={device}
  isActive={true}
  frameProcessor={frameProcessor}
/>

React Native Camera Kit:

<CameraKitCamera
  ref={cam => this.camera = cam}
  style={{flex: 1}}
  cameraOptions={{
    flashMode: 'auto',
    focusMode: 'on',
    zoomMode: 'on'
  }}
/>

Vision Camera offers more granular control over camera devices and supports frame processors, while React Native Camera Kit provides a simpler API for basic camera functionality. Vision Camera's approach is more flexible but requires more setup, whereas React Native Camera Kit is easier to implement for straightforward use cases.

An unified permissions API for React Native on iOS, Android and Windows.

Pros of react-native-permissions

  • Comprehensive permission handling for multiple platforms (iOS, Android, Windows)
  • Actively maintained with frequent updates and community support
  • Flexible API allowing for granular control over various permission types

Cons of react-native-permissions

  • Focuses solely on permissions, lacking camera functionality
  • May require additional setup and configuration for specific use cases
  • Potential for increased app size due to comprehensive permission handling

Code Comparison

react-native-permissions:

import { check, request, PERMISSIONS } from 'react-native-permissions';

const checkCameraPermission = async () => {
  const result = await check(PERMISSIONS.IOS.CAMERA);
  if (result === 'denied') {
    await request(PERMISSIONS.IOS.CAMERA);
  }
};

react-native-camera-kit:

import { CameraKitCamera } from 'react-native-camera-kit';

const checkCameraPermission = async () => {
  const isCameraAuthorized = await CameraKitCamera.checkDeviceCameraAuthorizationStatus();
  if (!isCameraAuthorized) {
    await CameraKitCamera.requestDeviceCameraAuthorization();
  }
};

The code comparison shows that react-native-permissions offers a more generalized approach to handling permissions, while react-native-camera-kit provides camera-specific functionality with built-in permission handling. react-native-permissions allows for more granular control over different permission types, whereas react-native-camera-kit simplifies camera-related operations.

:sunrise_over_mountains: A React Native module that allows you to use native UI to select media from the device library or directly from the camera.

Pros of react-native-image-picker

  • More comprehensive documentation and examples
  • Supports a wider range of image selection options (camera, gallery, custom)
  • Active community support and regular updates

Cons of react-native-image-picker

  • Larger package size and potentially more complex setup
  • May require additional configuration for advanced camera features

Code Comparison

react-native-image-picker:

import {launchCamera, launchImageLibrary} from 'react-native-image-picker';

const options = {
  mediaType: 'photo',
  quality: 1,
};

launchImageLibrary(options, (response) => {
  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else {
    const source = { uri: response.uri };
    // Use the image
  }
});

react-native-camera-kit:

import { CameraKitCameraScreen } from 'react-native-camera-kit';

<CameraKitCameraScreen
  actions={{ rightButtonText: 'Done', leftButtonText: 'Cancel' }}
  onBottomButtonPressed={(event) => this.onBottomButtonPressed(event)}
  flashImages={{
    on: require('./../images/flashOn.png'),
    off: require('./../images/flashOff.png'),
    auto: require('./../images/flashAuto.png')
  }}
  cameraFlipImage={require('./../images/cameraFlipIcon.png')}
  captureButtonImage={require('./../images/cameraButton.png')}
/>

Both libraries offer image picking and camera functionality, but react-native-image-picker provides a more straightforward API for basic image selection, while react-native-camera-kit offers more customization options for the camera interface.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

🎈 React Native Camera Kit

A high performance, easy to use, rock solid
camera library for React Native apps.

React Native Camera Kit is released under the MIT license. Current npm package version.

  • Cross Platform (iOS and Android)

  • Optimized for performance and high photo capture rate

  • QR / Barcode scanning support

  • Camera preview support in iOS simulator

Installation (RN > 0.60)

yarn add react-native-camera-kit
cd ios && pod install && cd ..

Android: Review your Kotlin configuration to ensure it's compatible with this library.

Permissions

You must use a separate library for prompting the user for permissions before rendering the <Camera .../> component.
We recommend zoontek's library, react-native-permissions: https://github.com/zoontek/react-native-permissions#ios-flow

If you fail to prompt for permission, the camera will appear blank / black.

Why no permissions API?

Conceptually, permissions are simple: Granted / Denied.
However, in reality it's not that simple due to privacy enhancements on iOS and Android.

Here's an example diagram from react-native-permissions's README, which illustrates the complexity of the user-experience, which we don't want to duplicate in a camera library:

   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
   ┃ check(PERMISSIONS.IOS.CAMERA) ┃
   ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                   │
       Is the feature available
           on this device ?
                   │           ╔════╗
                   ├───────────║ NO ║──────────────┐
                   │           ╚════╝              │
                ╔═════╗                            ▼
                ║ YES ║                 ┌─────────────────────┐
                ╚═════╝                 │ RESULTS.UNAVAILABLE │
                   │                    └─────────────────────┘
           Is the permission
             requestable ?
                   │           ╔════╗
                   ├───────────║ NO ║──────────────┐
                   │           ╚════╝              │
                ╔═════╗                            ▼
                ║ YES ║                  ┌───────────────────┐
                ╚═════╝                  │ RESULTS.BLOCKED / │
                   │                     │ RESULTS.LIMITED / │
                   │                     │  RESULTS.GRANTED  │
                   ▼                     └───────────────────┘
          ┌────────────────┐
          │ RESULTS.DENIED │
          └────────────────┘
                   │
                   ▼
  ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
  ┃ request(PERMISSIONS.IOS.CAMERA) ┃
  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                   │
         Does the user accept
            the request ?
                   │           ╔════╗
                   ├───────────║ NO ║──────────────┐
                   │           ╚════╝              │
                ╔═════╗                            ▼
                ║ YES ║                   ┌─────────────────┐
                ╚═════╝                   │ RESULTS.BLOCKED │
                   │                      └─────────────────┘
                   ▼
          ┌─────────────────┐
          │ RESULTS.GRANTED │
          └─────────────────┘

In earlier versions of react-native-camera-kit, permissions were provided with an API, but for the above reasons, these APIs will be removed.

Android

Add the following uses-permission to your AndroidManifest.xml (usually found at: android/src/main/)

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

iOS

Add the following usage descriptions to your Info.plist (usually found at: ios/PROJECT_NAME/)

<key>NSCameraUsageDescription</key>
<string>For taking photos</string>

<key>NSPhotoLibraryUsageDescription</key>
<string>For saving photos</string>

Running the example project

  • yarn bootstrap
  • yarn example ios or yarn example android

Components

Camera

Barebones camera component if you need advanced/customized interface

import { Camera, CameraType } from 'react-native-camera-kit';
<Camera
  ref={(ref) => (this.camera = ref)}
  cameraType={CameraType.Back} // front/back(default)
  flashMode="auto"
/>

Barcode / QR Code Scanning

Additionally, the Camera can be used for barcode scanning

<Camera
  ...
  // Barcode props
  scanBarcode={true}
  onReadCode={(event) => Alert.alert('QR code found')} // optional
  showFrame={true} // (default false) optional, show frame with transparent layer (qr code or barcode will be read on this area ONLY), start animation for scanner, that stops when a code has been found. Frame always at center of the screen
  laserColor='red' // (default red) optional, color of laser in scanner frame
  frameColor='white' // (default white) optional, color of border of scanner frame
/>

Camera Props (Optional)

PropsTypeDescription
refRefReference on the camera view
styleStyleProp<ViewStyle>Style to apply on the camera view
flashMode'on'/'off'/'auto'Camera flash mode. Default: auto
focusMode'on'/'off'Camera focus mode. Default: on
zoomMode'on'/'off'Enable the pinch to zoom gesture. Default: on
zoomnumberControl the zoom. Default: 1.0
maxZoomnumberMaximum zoom allowed (but not beyond what camera allows). Default: undefined (camera default max)
onZoomFunctionCallback when user makes a pinch gesture, regardless of what the zoom prop was set to. Returned event contains zoom. Ex: onZoom={(e) => console.log(e.nativeEvent.zoom)}.
torchMode'on'/'off'Toggle flash light when camera is active. Default: off
cameraTypeCameraType.Back/CameraType.FrontChoose what camera to use. Default: CameraType.Back
onOrientationChangeFunctionCallback when physical device orientation changes. Returned event contains orientation. Ex: onOrientationChange={(event) => console.log(event.nativeEvent.orientation)}. Use import { Orientation } from 'react-native-camera-kit'; if (event.nativeEvent.orientation === Orientation.PORTRAIT) { ... } to understand the new value
Android only
onErrorFunctionAndroid only. Callback when camera fails to initialize. Ex: onError={(e) => console.log(e.nativeEvent.errorMessage)}.
shutterPhotoSoundbooleanAndroid only. Enable or disable the shutter sound when capturing a photo. Default: true
iOS only
ratioOverlay'int:int'Show a guiding overlay in the camera preview for the selected ratio. Does not crop image as of v9.0. Example: '16:9'
ratioOverlayColorColorAny color with alpha. Default: '#ffffff77'
resetFocusTimeoutnumberDismiss tap to focus after this many milliseconds. Default 0 (disabled). Example: 5000 is 5 seconds.
resetFocusWhenMotionDetectedBooleanDismiss tap to focus when focus area content changes. Native iOS feature, see documentation: https://developer.apple.com/documentation/avfoundation/avcapturedevice/1624644-subjectareachangemonitoringenabl?language=objc). Default true.
resizeMode'cover' / 'contain'Determines the scaling and cropping behavior of content within the view. cover (resizeAspectFill on iOS) scales the content to fill the view completely, potentially cropping content if its aspect ratio differs from the view. contain (resizeAspect on iOS) scales the content to fit within the view's bounds without cropping, ensuring all content is visible but may introduce letterboxing. Default behavior depends on the specific use case.
scanThrottleDelaynumberDuration between scan detection in milliseconds. Default 2000 (2s)
maxPhotoQualityPrioritization'balanced' / 'quality' / 'speed'iOS 13 and newer. 'speed' provides a 60-80% median capture time reduction vs 'quality' setting. Tested on iPhone 6S Max (66% faster) and iPhone 15 Pro Max (76% faster!). Default balanced
onCaptureButtonPressInFunctionCallback when iPhone capture button is pressed in or Android volume or camera button is pressed in. Ex: onCaptureButtonPressIn={() => console.log("volume button pressed in")}
onCaptureButtonPressOutFunctionCallback when iPhone capture button is released or Android volume or camera button is released. Ex: onCaptureButtonPressOut={() => console.log("volume button released")}
Barcode only
scanBarcodebooleanEnable barcode scanner. Default: false
showFramebooleanShow frame in barcode scanner. Default: false
barcodeFrameSizeobjectFrame size of barcode scanner. Default: { width: 300, height: 150 }
laserColorColorColor of barcode scanner laser visualization. Default: red
frameColorColorColor of barcode scanner frame visualization. Default: yellow
onReadCodeFunctionCallback when scanner successfully reads barcode. Returned event contains codeStringValue. Default: null. Ex: onReadCode={(event) => console.log(event.nativeEvent.codeStringValue)}

Imperative API

Note: Must be called on a valid camera ref

capture()

Capture image as JPEG.

A temporary file is created. You must move this file to a permanent location (e.g. the app's 'Documents' folder) if you need it beyond the current session of the app as it may be deleted when the user leaves the app. You can move files by using a file system library such as react-native-fs or expo-filesystem. (On Android we currently have an unsupported outputPath prop but it's subject to change at any time).

Note that the reason you're getting a URL despite it being a file is because Android 10+ encourages URIs. To keep things consistent regardless of settings or platform we always send back a URI.

const { uri } = await this.camera.capture();
// uri = 'file:///data/user/0/com.myorg.myapp/cache/ckcap123123123123.jpg'

If you want to store it permanently, here's an example using react-native-fs:

import RNFS from 'react-native-fs';
// [...]
let { uri } = await this.camera.capture();
if (uri.startsWith('file://')) {
  // Platform dependent, iOS & Android uses '/'
  const pathSplitter = '/';
  // file:///foo/bar.jpg => /foo/bar.jpg
  const filePath = uri.replace('file://', '');
  // /foo/bar.jpg => [foo, bar.jpg]
  const pathSegments = filePath.split(pathSplitter);
  // [foo, bar.jpg] => bar.jpg
  const fileName = pathSegments[pathSegments.length - 1];

  await RNFS.moveFile(filePath, `${RNFS.DocumentDirectoryPath}/${fileName}`);
  uri = `file://${destFilePath}`;
}

Using with Expo

If you are using Expo Managed Workflow, you can use this library with a third-party plugin expo-react-native-camera-kit.

See more here

Contributing

  • Pull Requests are welcome, if you open a pull request we will do our best to get to it in a timely manner
  • Pull Request Reviews are even more welcome! we need help testing, reviewing, and updating open PRs
  • If you are interested in contributing more actively, please contact us.

License

The MIT License.

See LICENSE

NPM DownloadsLast 30 Days