# react-native-camera **Repository Path**: loong-react-native/react-native-camera ## Basic Information - **Project Name**: react-native-camera - **Description**: 摄像头调用组件 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-11-11 - **Last Updated**: 2024-06-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # React Native Camera [![Backers on Open Collective](https://opencollective.com/react-native-camera/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/react-native-camera/sponsors/badge.svg)](#sponsors) [![npm version](https://badge.fury.io/js/react-native-camera.svg)](http://badge.fury.io/js/react-native-camera) [![npm downloads](https://img.shields.io/npm/dm/react-native-camera.svg)](https://www.npmjs.com/package/react-native-camera) ## Sponsors If you use this library on your commercial/personal projects, you can help us by funding the work on specific issues that you choose by using IssueHunt.io! This gives you the power to prioritize our work and support the project contributors. Moreover it'll guarantee the project will be updated and maintained in the long run. [![issuehunt-image](https://issuehunt.io/static/embed/issuehunt-button-v1.svg)](https://issuehunt.io/repos/33218414) ## Open Collective You can also fund this project using open collective ### Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/react-native-camera#backer)] ### Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/react-native-camera#sponsor)] The comprehensive camera module for React Native. Supports: - photographs. - videos - face detection (Android & iOS only) - barcode scanning - text recognition (optional installation for iOS using CocoaPods) ## Tidelift [Get supported react-native-camera with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-react-native-camera?utm_source=npm-react-native-camera&utm_medium=referral&utm_campaign=readme) ![tidelift](https://tidelift.com/badges/github/react-native-community/react-native-camera) ### Example import ```jsx import { RNCamera, FaceDetector } from 'react-native-camera'; ``` #### How to use master branch? We recommend using the releases from npm, however if you need some features that are not published on npm yet you can install react-native-camera from git. **yarn**: `yarn add react-native-camera@git+https://git@github.com/react-native-community/react-native-camera.git` **npm**: `npm install --save react-native-camera@git+https://git@github.com/react-native-community/react-native-camera.git` ### 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 me (same username on Twitter, Facebook, etc.) Thanks! - We are now on [Open Collective](https://opencollective.com/react-native-camera#sponsor)! Contributions are appreciated and will be used to fund core contributors. [more details](#open-collective) - If you want to help us coding, join Expo slack https://slack.expo.io/, so we can chat over there. (#react-native-camera) ##### Permissions To use the camera on Android you must ask for camera permission: ```java ``` To enable `video recording` feature you have to add the following code to the `AndroidManifest.xml`: ```java ``` ![5j2jduk](https://cloud.githubusercontent.com/assets/2302315/22190752/6bc6ccd0-e0da-11e6-8e2f-6f22a3567a57.gif) ## Migrating from RCTCamera to RNCamera See this [doc](./docs/migration.md) ## Migrating from version 1.x to 2.x See this [doc](./docs/migrationV2.md) ### RNCamera Docs [RNCamera](./docs/RNCamera.md) ### Docs old RCTCamera [RCTCamera](./docs/RCTCamera.md) ## Getting started ### Requirements 1. JDK >= 1.7 (if you run on 1.6 you will get an error on "\_cameras = new HashMap<>();") 2. With iOS 10 and higher you need to add the "Privacy - Camera Usage Description" key to the Info.plist of your project. This should be found in 'your_project/ios/your_project/Info.plist'. Add the following code: ``` NSCameraUsageDescription Your message to user when the camera is accessed for the first time NSPhotoLibraryUsageDescription Your message to user when the photo library is accessed for the first time NSMicrophoneUsageDescription Your message to user when the microphone is accessed for the first time ``` 3. On Android, you require `buildToolsVersion` of `25.0.2+`. _This should easily and automatically be downloaded by Android Studio's SDK Manager._ 4. On iOS 11 and later you need to add `NSPhotoLibraryAddUsageDescription` key to the Info.plist. This key lets you describe the reason your app seeks write-only access to the user’s photo library. Info.plist can be found in 'your_project/ios/your_project/Info.plist'. Add the following code: ``` NSPhotoLibraryAddUsageDescription Your message to user when the photo library is accessed for the first time ``` ### Mostly automatic install with react-native 1. `npm install react-native-camera --save` 2. `react-native link react-native-camera` _To install it with Windows, see manual install below_ ### Mostly automatic install with CocoaPods 1. `npm install react-native-camera --save` 2. Add the plugin dependency to your Podfile, pointing at the path where NPM installed it: ```obj-c pod 'react-native-camera', path: '../node_modules/react-native-camera' ``` 3. Run `pod install` _Note:_ You might need to adjust your Podfile following the example below: ```ruby target 'yourTargetName' do # See http://facebook.github.io/react-native/docs/integration-with-existing-apps.html#configuring-cocoapods-dependencies pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'Core', 'CxxBridge', # Include this for RN >= 0.47 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 'RCTText', 'RCTNetwork', 'RCTWebSocket', # Needed for debugging 'RCTAnimation', # Needed for FlatList and animations running on native UI thread # Add any other subspecs you want to use in your project ] # Explicitly include Yoga if you are using RN >= 0.42.0 pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' # Third party deps podspec link pod 'react-native-camera', path: '../node_modules/react-native-camera' end post_install do |installer| installer.pods_project.targets.each do |target| if target.name == "React" target.remove_from_project end end end ``` ### Manual install #### iOS 1. `npm install react-native-camera --save` 2. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]` 3. Go to `node_modules` ➜ `react-native-camera` and add `RNCamera.xcodeproj` 4. Expand the `RNCamera.xcodeproj` ➜ `Products` folder 5. In XCode, in the project navigator, select your project. Add `libRNCamera.a` to your project's `Build Phases` ➜ `Link Binary With Libraries` 6. Click `RNCamera.xcodeproj` in the project navigator and go the `Build Settings` tab. Make sure 'All' is toggled on (instead of 'Basic'). In the `Search Paths` section, look for `Header Search Paths` and make sure it contains both `$(SRCROOT)/../../react-native/React` and `$(SRCROOT)/../../../React` - mark both as `recursive`. ### Face Detection or Text Recognition Steps Face Detection/Text Recognition are optional on iOS. If you want them, you are going to need to install Google Mobile Vision frameworks in your project, as mentioned in the next section. ##### No Face Detection steps If you do not need it and do not want to install the GMV frameworks, open your app xcode project, on the Project Navigator, expand the RNCamera project, right click on the FaceDetector folder and delete it (move to trash, if you want). If you keep that folder and do not follow the GMV installation steps, your project will not compile. If you want to make this automatic, you can add a postinstall script to your app `package.json`. Inside the `postinstall_project` there is a xcode project ready with the folder removed (we opened xcode, removed the folder from the project and copied the resulting project file). The post install script is: ``` #!/bin/bash echo "Creating project without FaceDetector" if [ -e node_modules/react-native-camera/ios/FaceDetector ] ; then rm -rf node_modules/react-native-camera/ios/FaceDetector fi cp node_modules/react-native-camera/postinstall_project/projectWithoutFaceDetection.pbxproj node_modules/react-native-camera/ios/RNCamera.xcodeproj/project.pbxproj ``` And add something like this to the `scripts` section in your `package.json`: _Note:_ The face detection/text recognition code is excluded by default for the **CocoaPods** installation. ``` "postinstall": "./scripts/post.sh", ``` ##### Installing GMV frameworks GMV (Google Mobile Vision) is used for Face detection/Text recognition by the iOS RNCamera. You have to link the google frameworks to your project to successfully compile the RNCamera project. ###### CocoaPods Path (The only option for Text Recognition) Modify the dependency towards `react-native-camera` in your `Podfile`, from ``` pod 'react-native-camera', path: '../node_modules/react-native-camera' ``` to (for Face Detection) ``` pod 'react-native-camera', path: '../node_modules/react-native-camera', subspecs: [ 'FaceDetector' ] ``` or to (for Text Recognition) ``` pod 'react-native-camera', path: '../node_modules/react-native-camera', subspecs: [ 'TextDetector' ] ``` ###### Additional steps for Text Recognition Text recognition for iOS uses Firebase MLKit which requires setting up Firebase project for your app. If you have not already added Firebase to your app, please follow the steps described in [getting started guide](https://firebase.google.com/docs/ios/setup). In short, you would need to 1. Register your app in Firebase console. 2. Download `GoogleService-Info.plist` and add it to your project 3. Add `pod 'Firebase/Core'` to your podfile 4. In your `AppDelegate.m` file add the following lines: ```objective-c #import // <--- add this ... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; // <--- add this ... } ``` _Note:_ Text recognition is currently available only via CocoaPods Path. - If you have issues with duplicate symbols you will need to enable dead code stripping option in your Xcode (Target > Build Settings > search for "Dead code stripping") [see here](https://github.com/firebase/quickstart-ios/issues/487#issuecomment-415313053). - If you are using `pod Firebase/Core` with a version set below 5.13 you might want to add `pod 'GoogleAppMeasurement', '~> 5.3.0'` to your podfile ###### Non-CocoaPods Path 1. Download: Google Symbol Utilities: https://www.gstatic.com/cpdc/dbffca986f6337f8-GoogleSymbolUtilities-1.1.1.tar.gz Google Utilities: https://dl.google.com/dl/cpdc/978f81964b50a7c0/GoogleUtilities-1.3.2.tar.gz Google Mobile Vision: https://dl.google.com/dl/cpdc/df83c97cbca53eaf/GoogleMobileVision-1.1.0.tar.gz Google network Utilities: https://dl.google.com/dl/cpdc/54fd7b7ef8fd3edc/GoogleNetworkingUtilities-1.2.2.tar.gz Google Interchange Utilities: https://dl.google.com/dl/cpdc/1a7f7ba905b2c029/GoogleInterchangeUtilities-1.2.2.tar.gz 2. Extract everything to one folder. Delete "BarcodeDetector" and "copy" folders from Google Mobile Vision. 3. Open XCode, right click on your project and choose "New Group". Rename the new folder to "Frameworks". Right click on "Frameworks" and select "add files to 'YOUR_PROJECT'". Select all content from the folder of step 2, click on Options. Select "Copy items if needed", leave "Create groups" selected and choose all your targets on the "Add to targets" section. Then, click on "Add". 4. On your target -> Build Phases -> Link Binary with Libraries -> add AddressBook.framework 5. On your target -> Build Settings -> Other Linker Flags -> add -lz, -ObjC and -lc++ 6. To force indexing and prevent errors, restart xcode and reopen your project again before compiling. #### Android 1. `npm install react-native-camera --save` 2. Open up `android/app/src/main/java/[...]/MainApplication.java` - Add `import org.reactnative.camera.RNCameraPackage;` to the imports at the top of the file - Add `new RNCameraPackage()` to the list returned by the `getPackages()` method. Add a comma to the previous item if there's already something there. 3. Append the following lines to `android/settings.gradle`: ```gradle include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android') ``` 4. Insert the following lines in `android/app/build.gradle`: inside the dependencies block: ```gradle implementation project(':react-native-camera') ``` inside defaultConfig block insert either: ```gradle android { ... defaultConfig { ... missingDimensionStrategy 'react-native-camera', 'general' <-- insert this line } } ``` or, if using MLKit for text/face/barcode recognition: ```gradle android { ... defaultConfig { ... missingDimensionStrategy 'react-native-camera', 'mlkit' <-- insert this line } } ``` 5. Declare the permissions in your Android Manifest (required for `video recording` feature) ```xml ``` 6. Add jitpack to android/build.gradle ```gradle allprojects { repositories { maven { url "https://jitpack.io" } maven { url "https://maven.google.com" } } } ``` 7. Additional steps for using MLKit for text/face/barcode recognition 7.1. Using Firebase MLKit requires seting up Firebase project for your app. If you have not already added Firebase to your app, please follow the steps described in [getting started guide](https://firebase.google.com/docs/android/setup). In short, you would need to - Register your app in Firebase console. - Download google-services.json and place it in `android/app/` - add the folowing to project level build.gradle: ```gradle buildscript { dependencies { // Add this line classpath 'com.google.gms:google-services:4.0.1' <-- you might want to use different version } } ``` - add to the bottom of `android/app/build.gradle` file ```gradle apply plugin: com.google.gms.google-services' ``` 7.2. Configure your app to automatically download the ML model to the device after your app is installed from the Play Store. If you do not enable install-time model downloads, the model will be downloaded the first time you run the on-device detector. Requests you make before the download has completed will produce no results. ```xml ... ``` The current Android library defaults to the below values for the Google SDK and Libraries, ```gradle def DEFAULT_COMPILE_SDK_VERSION = 26 def DEFAULT_BUILD_TOOLS_VERSION = "26.0.2" def DEFAULT_TARGET_SDK_VERSION = 26 def DEFAULT_GOOGLE_PLAY_SERVICES_VERSION = "12.0.1" def DEFAULT_SUPPORT_LIBRARY_VERSION = "27.1.0" ``` You can override this settings by adding a Project-wide gradle configuration properties for use by all modules in your ReactNative project by adding the below to `android/build.gradle` file, ```gradle buildscript {...} allprojects {...} /** * Project-wide gradle configuration properties for use by all modules */ ext { compileSdkVersion = 26 targetSdkVersion = 26 buildToolsVersion = "26.0.2" googlePlayServicesVersion = "12.0.1" googlePlayServicesVisionVersion = "15.0.2" supportLibVersion = "27.1.0" } ``` The above settings in the ReactNative project over-rides the values present in the `react-native-camera` module. For your reference below is the `android/build.gradle` file of the module. ```gradle def safeExtGet(prop, fallback) { rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback } buildscript { repositories { google() maven { url 'https://maven.google.com' } jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' } } apply plugin: 'com.android.library' android { compileSdkVersion safeExtGet('compileSdkVersion', 26) buildToolsVersion safeExtGet('buildToolsVersion', '26.0.2') defaultConfig { minSdkVersion safeExtGet('minSdkVersion', 16) targetSdkVersion safeExtGet('targetSdkVersion', 26) } flavorDimensions "react-native-camera" productFlavors { general { dimension "react-native-camera" } mlkit { dimension "react-native-camera" } } sourceSets { main { java.srcDirs = ['src/main/java'] } general { java.srcDirs = ['src/general/java'] } mlkit { java.srcDirs = ['src/mlkit/java'] } } lintOptions { abortOnError false warning 'InvalidPackage' } } repositories { google() mavenCentral() maven { url 'https://maven.google.com' } maven { url "https://jitpack.io" } maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } dependencies { compileOnly 'com.facebook.react:react-native:+' compileOnly 'com.facebook.infer.annotation:infer-annotation:+' implementation "com.google.zxing:core:3.3.0" implementation "com.drewnoakes:metadata-extractor:2.9.1" generalImplementation "com.google.android.gms:play-services-vision:${safeExtGet('google-services', '17.0.2')}" implementation "com.android.support:exifinterface:${safeExtGet('supportLibVersion', '27.1.0')}" implementation "com.android.support:support-annotations:${safeExtGet('supportLibVersion', '27.1.0')}" implementation "com.android.support:support-v4:${safeExtGet('supportLibVersion', '27.1.0')}" mlkitImplementation "com.google.firebase:firebase-ml-vision:${safeExtGet('firebase-ml-vision', '18.0.2')}" mlkitImplementation "com.google.firebase:firebase-ml-vision-face-model:17.0.2" } ``` If you are using a version of `googlePlayServicesVersion` that does not have `play-services-vision`, you can specify a different version of `play-services-vision` by adding `googlePlayServicesVisionVersion` to the project-wide properties ``` ext { compileSdkVersion = 26 targetSdkVersion = 26 buildToolsVersion = "26.0.2" googlePlayServicesVersion = "16.0.1" googlePlayServicesVisionVersion = "15.0.2" supportLibVersion = "27.1.0" } ``` #### Windows 1. `npm install react-native-camera --save` 2. Link the library as described here: [react-native-windows / LinkingLibrariesWindows.md](https://github.com/Microsoft/react-native-windows/blob/master/docs/LinkingLibrariesWindows.md) For the last step of this guide, you have to add the following things to your `MainReactNativeHost.cs`: - in the import section at the very top: `using RNCamera;` - in `protected override List Packages => new List` add a new line with `new RNCameraPackage()` 3. Add the capabilities (permissions) for the webcam and microphone as described here: [docs.microsoft / audio-video-camera](https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/simple-camera-preview-access#add-capability-declarations-to-the-app-manifest) 4. Use `RCTCamera` (RNCamera is not supported yet) like described above Follow the [Q & A](./docs/QA.md) section if you are having compilation issues. ## Usage ### RNCamera Take a look into this [documentation](./docs/RNCamera.md). ### RCTCamera Since `1.0.0`, RCTCamera is deprecated, but if you want to use it, you can see its [documentation](./docs/RCTCamera.md). --- Thanks to Brent Vatne (@brentvatne) for the `react-native-video` module which provided me with a great example of how to set up this module.