├── .github
├── ISSUE_TEMPLATE.md
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .weexpack.cache
├── Example
├── .flowconfig
├── .gitignore
├── .watchmanconfig
├── App.js
├── android
│ ├── Example.iml
│ ├── app
│ │ ├── BUCK
│ │ ├── build.gradle
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ └── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ ├── MainActivity.java
│ │ │ │ └── MainApplication.java
│ │ │ └── res
│ │ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── index.android.js
├── index.ios.js
├── ios
│ ├── Example.xcodeproj
│ │ ├── project.pbxproj
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── Example.xcscheme
│ └── Example
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.m
│ │ ├── Base.lproj
│ │ └── LaunchScreen.xib
│ │ ├── Images.xcassets
│ │ └── AppIcon.appiconset
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ └── main.m
└── package.json
├── LICENSE.md
├── README.md
├── android
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── imagepicker
│ │ │ ├── ImagePickerModule.java
│ │ │ ├── ImagePickerPackage.java
│ │ │ ├── ResponseHelper.java
│ │ │ ├── media
│ │ │ ├── ImageConfig.java
│ │ │ └── VideoConfig.java
│ │ │ ├── permissions
│ │ │ ├── OnImagePickerPermissionsCallback.java
│ │ │ ├── PermissionUtils.java
│ │ │ └── PermissionsHelper.java
│ │ │ └── utils
│ │ │ ├── ButtonsHelper.java
│ │ │ ├── MediaUtils.java
│ │ │ ├── ReadableMapUtils.java
│ │ │ ├── RealPathUtil.java
│ │ │ └── UI.java
│ └── res
│ │ ├── layout
│ │ └── list_item.xml
│ │ ├── values
│ │ └── themes.xml
│ │ └── xml
│ │ └── provider_paths.xml
│ └── test
│ └── java
│ └── com
│ └── imagepicker
│ └── testing
│ ├── ImagePickerModuleTest.java
│ ├── SampleCallback.java
│ ├── TestableImagePickerModule.java
│ └── media
│ └── ImageConfigTest.java
├── images
├── android-image.png
└── ios-image.png
├── index.d.ts
├── index.js
├── ios
├── ImagePickerManager.h
├── ImagePickerManager.m
├── RNImagePicker.xcodeproj
│ └── project.pbxproj
└── WeexImagePicker.xcodeproj
│ └── project.xcworkspace
│ └── contents.xcworkspacedata
├── package.json
├── playground
└── ios
│ └── WeexDemo.xcodeproj
│ └── project.xcworkspace
│ └── contents.xcworkspacedata
├── react-native-image-picker.podspec
└── test
├── ios
└── Test.xcodeproj
│ └── project.xcworkspace
│ └── contents.xcworkspacedata
└── playground
└── ios
└── WeexDemo.xcodeproj
└── project.xcworkspace
└── contents.xcworkspacedata
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | * Please read the following carefully before opening a new issue.
2 | Your issue may be closed if it does not provide the information required by this template.
3 |
4 | --- Delete everything above this line ---
5 |
6 | ### Description
7 |
8 | Explain what you did, what you expected to happen, and what actually happens.
9 |
10 | ### How to repeat issue and example
11 |
12 | Your explanation here and source code or link
13 |
14 | ### Solution
15 |
16 | What needs to be done to address this issue? Ideally, provide a pull request with a fix.
17 |
18 | ### Additional Information
19 |
20 | * React Native version: [FILL THIS OUT: Be specific, filling out "latest" here is not enough.]
21 | * Platform: [FILL THIS OUT: iOS, Android, or both?]
22 | * Development Operating System: [FILL THIS OUT: Are you developing on MacOS, Linux, or Windows?]
23 | * Dev tools: [FILL THIS OUT: Xcode or Android Studio version, iOS or Android SDK version, if applicable] navigation crash for Android
24 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Thanks for submitting a PR! Please read these instructions carefully:
2 |
3 | - [ ] Explain the **motivation** for making this change.
4 | - [ ] Provide a **test plan** demonstrating that the code is solid.
5 | - [ ] Match the **code formatting** of the rest of the codebase.
6 | - [ ] Target the `master` branch, NOT a "stable" branch.
7 |
8 | ## Motivation (required)
9 |
10 | What existing problem does the pull request solve?
11 |
12 | ## Test Plan (required)
13 |
14 | A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI or updates the website. See [What is a Test Plan?][1] to learn more.
15 |
16 | If you have added code that should be tested, add tests.
17 |
18 | [1]: https://medium.com/@martinkonicek/what-is-a-test-plan-8bfc840ec171#.y9lcuqqi9
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Android Studio ###
2 | .idea/
3 | .gradle/
4 | local.properties
5 |
6 | ### Xcode ###
7 |
8 | ## Build generated
9 | build/
10 | DerivedData/
11 |
12 | ## Various settings
13 | *.pbxuser
14 | !default.pbxuser
15 | *.mode1v3
16 | !default.mode1v3
17 | *.mode2v3
18 | !default.mode2v3
19 | *.perspectivev3
20 | !default.perspectivev3
21 | xcuserdata/
22 |
23 | ## Other
24 | *.moved-aside
25 | *.xccheckout
26 | *.xcscmblueprint
27 |
28 | ### /Xcode ###
29 |
30 | ### OS X
31 | .DS_Store
32 |
33 | ### Node
34 | node_modules
35 | *.log
36 | yarn.lock
37 |
38 | ## Android iml
39 | *.iml
40 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | Example/
2 | images/
3 | node_modules/
4 |
--------------------------------------------------------------------------------
/.weexpack.cache:
--------------------------------------------------------------------------------
1 | {
2 | "latestVersion": "1.0.1"
3 | }
--------------------------------------------------------------------------------
/Example/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 |
3 | # We fork some components by platform.
4 | .*/*.web.js
5 | .*/*.android.js
6 |
7 | # Some modules have their own node_modules with overlap
8 | .*/node_modules/node-haste/.*
9 |
10 | # Ugh
11 | .*/node_modules/babel.*
12 | .*/node_modules/babylon.*
13 | .*/node_modules/invariant.*
14 |
15 | # Ignore react and fbjs where there are overlaps, but don't ignore
16 | # anything that react-native relies on
17 | .*/node_modules/fbjs/lib/Map.js
18 | .*/node_modules/fbjs/lib/Promise.js
19 | .*/node_modules/fbjs/lib/fetch.js
20 | .*/node_modules/fbjs/lib/ExecutionEnvironment.js
21 | .*/node_modules/fbjs/lib/isEmpty.js
22 | .*/node_modules/fbjs/lib/crc32.js
23 | .*/node_modules/fbjs/lib/ErrorUtils.js
24 |
25 | # Flow has a built-in definition for the 'react' module which we prefer to use
26 | # over the currently-untyped source
27 | .*/node_modules/react/react.js
28 | .*/node_modules/react/lib/React.js
29 | .*/node_modules/react/lib/ReactDOM.js
30 |
31 | # Ignore commoner tests
32 | .*/node_modules/commoner/test/.*
33 |
34 | # See https://github.com/facebook/flow/issues/442
35 | .*/react-tools/node_modules/commoner/lib/reader.js
36 |
37 | # Ignore jest
38 | .*/node_modules/jest-cli/.*
39 |
40 | # Ignore Website
41 | .*/website/.*
42 |
43 | [include]
44 |
45 | [libs]
46 | node_modules/react-native/Libraries/react-native/react-native-interface.js
47 |
48 | [options]
49 | module.system=haste
50 |
51 | munge_underscores=true
52 |
53 | module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub'
54 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\)$' -> 'RelativeImageStub'
55 |
56 | suppress_type=$FlowIssue
57 | suppress_type=$FlowFixMe
58 | suppress_type=$FixMe
59 |
60 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-1]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
61 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-1]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
62 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
63 |
64 | [version]
65 | 0.21.0
66 |
--------------------------------------------------------------------------------
/Example/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | project.xcworkspace
24 |
25 | # Android/IJ
26 | #
27 | .idea
28 | .gradle
29 | local.properties
30 |
31 | # node.js
32 | #
33 | node_modules/
34 | npm-debug.log
35 |
--------------------------------------------------------------------------------
/Example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Example/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | AppRegistry,
4 | StyleSheet,
5 | Text,
6 | View,
7 | PixelRatio,
8 | TouchableOpacity,
9 | Image,
10 | } from 'react-native';
11 |
12 | import ImagePicker from 'react-native-image-picker';
13 |
14 | export default class App extends React.Component {
15 |
16 | state = {
17 | avatarSource: null,
18 | videoSource: null
19 | };
20 |
21 | selectPhotoTapped() {
22 | const options = {
23 | quality: 1.0,
24 | maxWidth: 500,
25 | maxHeight: 500,
26 | storageOptions: {
27 | skipBackup: true
28 | }
29 | };
30 |
31 | ImagePicker.showImagePicker(options, (response) => {
32 | console.log('Response = ', response);
33 |
34 | if (response.didCancel) {
35 | console.log('User cancelled photo picker');
36 | }
37 | else if (response.error) {
38 | console.log('ImagePicker Error: ', response.error);
39 | }
40 | else if (response.customButton) {
41 | console.log('User tapped custom button: ', response.customButton);
42 | }
43 | else {
44 | let source = { uri: response.uri };
45 |
46 | // You can also display the image using data:
47 | // let source = { uri: 'data:image/jpeg;base64,' + response.data };
48 |
49 | this.setState({
50 | avatarSource: source
51 | });
52 | }
53 | });
54 | }
55 |
56 | selectVideoTapped() {
57 | const options = {
58 | title: 'Video Picker',
59 | takePhotoButtonTitle: 'Take Video...',
60 | mediaType: 'video',
61 | videoQuality: 'medium'
62 | };
63 |
64 | ImagePicker.showImagePicker(options, (response) => {
65 | console.log('Response = ', response);
66 |
67 | if (response.didCancel) {
68 | console.log('User cancelled video picker');
69 | }
70 | else if (response.error) {
71 | console.log('ImagePicker Error: ', response.error);
72 | }
73 | else if (response.customButton) {
74 | console.log('User tapped custom button: ', response.customButton);
75 | }
76 | else {
77 | this.setState({
78 | videoSource: response.uri
79 | });
80 | }
81 | });
82 | }
83 |
84 | render() {
85 | return (
86 |
87 |
88 |
89 | { this.state.avatarSource === null ? Select a Photo :
90 |
91 | }
92 |
93 |
94 |
95 |
96 |
97 | Select a Video
98 |
99 |
100 |
101 | { this.state.videoSource &&
102 | {this.state.videoSource}
103 | }
104 |
105 | );
106 | }
107 |
108 | }
109 |
110 | const styles = StyleSheet.create({
111 | container: {
112 | flex: 1,
113 | justifyContent: 'center',
114 | alignItems: 'center',
115 | backgroundColor: '#F5FCFF'
116 | },
117 | avatarContainer: {
118 | borderColor: '#9B9B9B',
119 | borderWidth: 1 / PixelRatio.get(),
120 | justifyContent: 'center',
121 | alignItems: 'center'
122 | },
123 | avatar: {
124 | borderRadius: 75,
125 | width: 150,
126 | height: 150
127 | }
128 | });
129 |
--------------------------------------------------------------------------------
/Example/android/Example.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Example/android/app/BUCK:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | # To learn about Buck see [Docs](https://buckbuild.com/).
4 | # To run your application with Buck:
5 | # - install Buck
6 | # - `npm start` - to start the packager
7 | # - `cd android`
8 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US`
9 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
10 | # - `buck install -r android/app` - compile, install and run application
11 | #
12 |
13 | lib_deps = []
14 | for jarfile in glob(['libs/*.jar']):
15 | name = 'jars__' + re.sub(r'^.*/([^/]+)\.jar$', r'\1', jarfile)
16 | lib_deps.append(':' + name)
17 | prebuilt_jar(
18 | name = name,
19 | binary_jar = jarfile,
20 | )
21 |
22 | for aarfile in glob(['libs/*.aar']):
23 | name = 'aars__' + re.sub(r'^.*/([^/]+)\.aar$', r'\1', aarfile)
24 | lib_deps.append(':' + name)
25 | android_prebuilt_aar(
26 | name = name,
27 | aar = aarfile,
28 | )
29 |
30 | android_library(
31 | name = 'all-libs',
32 | exported_deps = lib_deps
33 | )
34 |
35 | android_library(
36 | name = 'app-code',
37 | srcs = glob([
38 | 'src/main/java/**/*.java',
39 | ]),
40 | deps = [
41 | ':all-libs',
42 | ':build_config',
43 | ':res',
44 | ],
45 | )
46 |
47 | android_build_config(
48 | name = 'build_config',
49 | package = 'com.autoblogvr',
50 | )
51 |
52 | android_resource(
53 | name = 'res',
54 | res = 'src/main/res',
55 | package = 'com.autoblogvr',
56 | )
57 |
58 | android_binary(
59 | name = 'app',
60 | package_type = 'debug',
61 | manifest = 'src/main/AndroidManifest.xml',
62 | keystore = '//android/keystores:debug',
63 | deps = [
64 | ':app-code',
65 | ],
66 | )
67 |
--------------------------------------------------------------------------------
/Example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation
19 | * entryFile: "index.android.js",
20 | *
21 | * // whether to bundle JS and assets in debug mode
22 | * bundleInDebug: false,
23 | *
24 | * // whether to bundle JS and assets in release mode
25 | * bundleInRelease: true,
26 | *
27 | * // whether to bundle JS and assets in another build variant (if configured).
28 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
29 | * // The configuration property can be in the following formats
30 | * // 'bundleIn${productFlavor}${buildType}'
31 | * // 'bundleIn${buildType}'
32 | * // bundleInFreeDebug: true,
33 | * // bundleInPaidRelease: true,
34 | * // bundleInBeta: true,
35 | *
36 | * // the root of your project, i.e. where "package.json" lives
37 | * root: "../../",
38 | *
39 | * // where to put the JS bundle asset in debug mode
40 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
41 | *
42 | * // where to put the JS bundle asset in release mode
43 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
44 | *
45 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
46 | * // require('./image.png')), in debug mode
47 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
48 | *
49 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
50 | * // require('./image.png')), in release mode
51 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
52 | *
53 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
54 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
55 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
56 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
57 | * // for example, you might want to remove it from here.
58 | * inputExcludes: ["android/**", "ios/**"]
59 | * ]
60 | */
61 |
62 | apply from: "../../node_modules/react-native/react.gradle"
63 |
64 | /**
65 | * Set this to true to create two separate APKs instead of one:
66 | * - An APK that only works on ARM devices
67 | * - An APK that only works on x86 devices
68 | * The advantage is the size of the APK is reduced by about 4MB.
69 | * Upload all the APKs to the Play Store and people will download
70 | * the correct one based on the CPU architecture of their device.
71 | */
72 | def enableSeparateBuildPerCPUArchitecture = false
73 |
74 | /**
75 | * Run Proguard to shrink the Java bytecode in release builds.
76 | */
77 | def enableProguardInReleaseBuilds = false
78 |
79 | android {
80 | compileSdkVersion 23
81 | buildToolsVersion "23.0.1"
82 |
83 | defaultConfig {
84 | applicationId "com.example"
85 | minSdkVersion 16
86 | targetSdkVersion 22
87 | versionCode 1
88 | versionName "1.0"
89 | ndk {
90 | abiFilters "armeabi-v7a", "x86"
91 | }
92 | }
93 | splits {
94 | abi {
95 | reset()
96 | enable enableSeparateBuildPerCPUArchitecture
97 | universalApk false // If true, also generate a universal APK
98 | include "armeabi-v7a", "x86"
99 | }
100 | }
101 | buildTypes {
102 | release {
103 | minifyEnabled enableProguardInReleaseBuilds
104 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
105 | }
106 | }
107 | // applicationVariants are e.g. debug, release
108 | applicationVariants.all { variant ->
109 | variant.outputs.each { output ->
110 | // For each separate APK per architecture, set a unique version code as described here:
111 | // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
112 | def versionCodes = ["armeabi-v7a":1, "x86":2]
113 | def abi = output.getFilter(OutputFile.ABI)
114 | if (abi != null) { // null for the universal-debug, universal-release variants
115 | output.versionCodeOverride =
116 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
117 | }
118 | }
119 | }
120 | }
121 |
122 | dependencies {
123 | compile fileTree(dir: "libs", include: ["*.jar"])
124 | compile "com.android.support:appcompat-v7:23.0.1"
125 | compile "com.facebook.react:react-native:+" // From node_modules
126 |
127 | compile project(':react-native-image-picker')
128 | }
129 |
--------------------------------------------------------------------------------
/Example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Disabling obfuscation is useful if you collect stack traces from production crashes
20 | # (unless you are using a system that supports de-obfuscate the stack traces).
21 | -dontobfuscate
22 |
23 | # React Native
24 |
25 | # Keep our interfaces so they can be used by other ProGuard rules.
26 | # See http://sourceforge.net/p/proguard/bugs/466/
27 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
28 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
29 |
30 | # Do not strip any method/class that is annotated with @DoNotStrip
31 | -keep @com.facebook.proguard.annotations.DoNotStrip class *
32 | -keepclassmembers class * {
33 | @com.facebook.proguard.annotations.DoNotStrip *;
34 | }
35 |
36 | -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
37 | void set*(***);
38 | *** get*();
39 | }
40 |
41 | -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; }
42 | -keep class * extends com.facebook.react.bridge.NativeModule { *; }
43 | -keepclassmembers,includedescriptorclasses class * { native ; }
44 | -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; }
45 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; }
46 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; }
47 |
48 | -dontwarn com.facebook.react.**
49 |
50 | # okhttp
51 |
52 | -keepattributes Signature
53 | -keepattributes *Annotation*
54 | -keep class com.squareup.okhttp.** { *; }
55 | -keep interface com.squareup.okhttp.** { *; }
56 | -dontwarn com.squareup.okhttp.**
57 |
58 | # okio
59 |
60 | -keep class sun.misc.Unsafe { *; }
61 | -dontwarn java.nio.file.*
62 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
63 | -dontwarn okio.**
64 |
65 | # stetho
66 |
67 | -dontwarn com.facebook.stetho.**
68 |
--------------------------------------------------------------------------------
/Example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
16 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Example/android/app/src/main/java/com/example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example;
2 |
3 | import com.facebook.react.ReactActivity;
4 |
5 | public class MainActivity extends ReactActivity {
6 |
7 | /**
8 | * Returns the name of the main component registered from JavaScript.
9 | * This is used to schedule rendering of the component.
10 | */
11 | @Override
12 | protected String getMainComponentName() {
13 | return "Example";
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Example/android/app/src/main/java/com/example/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.example;
2 |
3 | import android.app.Application;
4 | import android.util.Log;
5 |
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.shell.MainReactPackage;
11 |
12 | import java.util.Arrays;
13 | import java.util.List;
14 |
15 | import com.imagepicker.ImagePickerPackage;
16 |
17 | public class MainApplication extends Application implements ReactApplication {
18 |
19 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
20 | @Override
21 | public boolean getUseDeveloperSupport() {
22 | return BuildConfig.DEBUG;
23 | }
24 |
25 | @Override
26 | protected List getPackages() {
27 | return Arrays.asList(
28 | new MainReactPackage(),
29 | new ImagePickerPackage()
30 | );
31 | }
32 | };
33 |
34 | @Override
35 | public ReactNativeHost getReactNativeHost() {
36 | return mReactNativeHost;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/Example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/Example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/Example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/Example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Example
3 |
4 |
--------------------------------------------------------------------------------
/Example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.+'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | mavenLocal()
18 | jcenter()
19 | maven {
20 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
21 | url "$rootDir/../node_modules/react-native/android"
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | android.useDeprecatedNdk=true
21 |
--------------------------------------------------------------------------------
/Example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/Example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jun 09 11:55:07 EDT 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/Example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/Example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/Example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Example'
2 |
3 | include ':app'
4 |
5 | include ':react-native-image-picker'
6 | project(':react-native-image-picker').projectDir = new File(settingsDir, '../../android')
7 |
--------------------------------------------------------------------------------
/Example/index.android.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | AppRegistry
4 | } from 'react-native';
5 | import App from './App';
6 |
7 | class Example extends React.Component {
8 | render() {
9 | return (
10 |
11 | );
12 | }
13 | }
14 |
15 | AppRegistry.registerComponent('Example', () => Example);
16 |
--------------------------------------------------------------------------------
/Example/index.ios.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | AppRegistry
4 | } from 'react-native';
5 | import App from './App';
6 |
7 | class Example extends React.Component {
8 | render() {
9 | return (
10 |
11 | );
12 | }
13 | }
14 |
15 | AppRegistry.registerComponent('Example', () => Example);
16 |
--------------------------------------------------------------------------------
/Example/ios/Example.xcodeproj/xcshareddata/xcschemes/Example.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
38 |
39 |
44 |
45 |
46 |
47 |
53 |
54 |
55 |
56 |
57 |
58 |
68 |
70 |
76 |
77 |
78 |
79 |
80 |
81 |
87 |
89 |
95 |
96 |
97 |
98 |
100 |
101 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/Example/ios/Example/AppDelegate.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | * All rights reserved.
4 | *
5 | * This source code is licensed under the BSD-style license found in the
6 | * LICENSE file in the root directory of this source tree. An additional grant
7 | * of patent rights can be found in the PATENTS file in the same directory.
8 | */
9 |
10 | #import
11 |
12 | @interface AppDelegate : UIResponder
13 |
14 | @property (nonatomic, strong) UIWindow *window;
15 |
16 | @end
17 |
--------------------------------------------------------------------------------
/Example/ios/Example/AppDelegate.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | * All rights reserved.
4 | *
5 | * This source code is licensed under the BSD-style license found in the
6 | * LICENSE file in the root directory of this source tree. An additional grant
7 | * of patent rights can be found in the PATENTS file in the same directory.
8 | */
9 |
10 | #import "AppDelegate.h"
11 | #import "RCTBundleURLProvider.h"
12 | #import "RCTRootView.h"
13 |
14 | @implementation AppDelegate
15 |
16 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
17 | {
18 | NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
19 |
20 | RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"Example" initialProperties:nil launchOptions:launchOptions];
21 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
22 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
23 | UIViewController *rootViewController = [UIViewController new];
24 | rootViewController.view = rootView;
25 | self.window.rootViewController = rootViewController;
26 | [self.window makeKeyAndVisible];
27 | return YES;
28 | }
29 |
30 | @end
31 |
--------------------------------------------------------------------------------
/Example/ios/Example/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
21 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/Example/ios/Example/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/Example/ios/Example/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | NSAppTransportSecurity
26 |
27 | NSAllowsArbitraryLoads
28 |
29 |
30 | NSPhotoLibraryUsageDescription
31 |
32 | NSCameraUsageDescription
33 |
34 | NSMicrophoneUsageDescription
35 |
36 | UILaunchStoryboardName
37 | LaunchScreen
38 | UIRequiredDeviceCapabilities
39 |
40 | armv7
41 |
42 | UISupportedInterfaceOrientations
43 |
44 | UIInterfaceOrientationPortrait
45 | UIInterfaceOrientationLandscapeLeft
46 | UIInterfaceOrientationLandscapeRight
47 |
48 | UIViewControllerBasedStatusBarAppearance
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/Example/ios/Example/main.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | * All rights reserved.
4 | *
5 | * This source code is licensed under the BSD-style license found in the
6 | * LICENSE file in the root directory of this source tree. An additional grant
7 | * of patent rights can be found in the PATENTS file in the same directory.
8 | */
9 |
10 | #import
11 |
12 | #import "AppDelegate.h"
13 |
14 | int main(int argc, char * argv[]) {
15 | @autoreleasepool {
16 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Example",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "start": "node node_modules/react-native/local-cli/cli.js start",
7 | "adb-reverse": "adb reverse tcp:8081 tcp:8081"
8 | },
9 | "dependencies": {
10 | "react": "15.4.1",
11 | "react-native": "^0.40.0",
12 | "react-native-image-picker": "file:../"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Marc Shilling
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # React Native Image Picker [](https://badge.fury.io/js/react-native-image-picker) [](https://www.npmjs.org/package/react-native-image-picker)   [](https://gitter.im/react-native-image-picker/Lobby)
3 |
4 | A React Native module that allows you to use native UI to select a photo/video from the device library or directly from the camera, like so:
5 |
6 | iOS | Android
7 | ------- | ----
8 |
|
9 |
10 | #### _Before you open an issue_
11 | This library started as a basic bridge of the native iOS image picker, and I want to keep it that way. As such, functionality beyond what the native `UIImagePickerController` supports will not be supported here. **Multiple image selection, more control over the crop tool, and landscape support** are things missing from the native iOS functionality - **not issues with my library**. If you need these things, [react-native-image-crop-picker](https://github.com/ivpusic/react-native-image-crop-picker) might be a better choice for you.
12 |
13 | ## Table of contents
14 | - [Install](#install)
15 | - [Usage](#usage)
16 | - [Direct launch](#directly-launching-the-camera-or-image-library)
17 | - [Options](#options)
18 | - [Response object](#the-response-object)
19 |
20 | ## Install
21 |
22 | ### NOTE: THIS PACKAGE IS NOW BUILT FOR REACT NATIVE 0.40 OR GREATER! IF YOU NEED TO SUPPORT REACT NATIVE < 0.40, YOU SHOULD INSTALL THIS PACKAGE `@0.24`
23 |
24 | `npm install react-native-image-picker@latest --save`
25 |
26 | ### Automatic Installation
27 |
28 | `react-native link`
29 |
30 | IMPORTANT NOTE: You'll still need to perform step 4 for iOS and steps 2, 3, and 5 for Android of the manual instructions below.
31 |
32 | ### Manual Installation
33 |
34 | #### iOS
35 |
36 | 1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ `Add Files to <...>`
37 | 2. Go to `node_modules` ➜ `react-native-image-picker` ➜ `ios` ➜ select `RNImagePicker.xcodeproj`
38 | 3. Add `RNImagePicker.a` to `Build Phases -> Link Binary With Libraries`
39 | 4. For iOS 10+, Add the `NSPhotoLibraryUsageDescription`, `NSCameraUsageDescription`, and `NSMicrophoneUsageDescription` (if allowing video) keys to your `Info.plist` with strings describing why your app needs these permissions. **Note: You will get a SIGABRT crash if you don't complete this step**
40 | 5. Compile and have fun
41 |
42 | #### Android
43 | 1. Add the following lines to `android/settings.gradle`:
44 | ```gradle
45 | include ':react-native-image-picker'
46 | project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
47 | ```
48 |
49 | 2. Update the android build tools version to `2.2.+` in `android/build.gradle`:
50 | ```gradle
51 | buildscript {
52 | ...
53 | dependencies {
54 | classpath 'com.android.tools.build:gradle:2.2.+' // <- USE 2.2.+ version
55 | }
56 | ...
57 | }
58 | ...
59 | ```
60 |
61 | 3. Update the gradle version to `2.14.1` in `android/gradle/wrapper/gradle-wrapper.properties`:
62 | ```
63 | ...
64 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
65 | ```
66 |
67 | 4. Add the compile line to the dependencies in `android/app/build.gradle`:
68 | ```gradle
69 | dependencies {
70 | compile project(':react-native-image-picker')
71 | }
72 | ```
73 |
74 | 5. Add the required permissions in `AndroidManifest.xml`:
75 | ```xml
76 |
77 |
78 | ```
79 |
80 | 6. Add the import and link the package in `MainApplication.java`:
81 | ```java
82 | import com.imagepicker.ImagePickerPackage; // <-- add this import
83 |
84 | public class MainApplication extends Application implements ReactApplication {
85 | @Override
86 | protected List getPackages() {
87 | return Arrays.asList(
88 | new MainReactPackage(),
89 | new ImagePickerPackage() // <-- add this line
90 | // OR if you want to customize dialog style
91 | new ImagePickerPackage(R.style.my_dialog_style)
92 | );
93 | }
94 | }
95 | ```
96 |
97 | ##### Android (Optional)
98 |
99 | Customization settings of dialog `android/app/res/values/themes.xml`:
100 | ```xml
101 |
102 |
103 |
113 |
114 | ```
115 |
116 | If `MainActivity` is not instance of `ReactActivity`, you will need to implement `OnImagePickerPermissionsCallback` to `MainActivity`:
117 | ```java
118 | import com.imagepicker.permissions.OnImagePickerPermissionsCallback; // <- add this import
119 | import com.facebook.react.modules.core.PermissionListener; // <- add this import
120 |
121 | public class MainActivity extends YourActivity implements OnImagePickerPermissionsCallback {
122 | private PermissionListener listener; // <- add this attribute
123 |
124 | // Your methods here
125 |
126 | // Copy from here
127 |
128 | @Override
129 | public void setPermissionListener(PermissionListener listener)
130 | {
131 | this.listener = listener;
132 | }
133 |
134 | @Override
135 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
136 | {
137 | if (listener != null)
138 | {
139 | listener.onRequestPermissionsResult(requestCode, permissions, grantResults);
140 | }
141 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
142 | }
143 |
144 | // To here
145 | }
146 | ```
147 | This code allows to pass result of request permissions to native part.
148 |
149 | ## Usage
150 |
151 | ```javascript
152 | var ImagePicker = require('react-native-image-picker');
153 |
154 | // More info on all the options is below in the README...just some common use cases shown here
155 | var options = {
156 | title: 'Select Avatar',
157 | customButtons: [
158 | {name: 'fb', title: 'Choose Photo from Facebook'},
159 | ],
160 | storageOptions: {
161 | skipBackup: true,
162 | path: 'images'
163 | }
164 | };
165 |
166 | /**
167 | * The first arg is the options object for customization (it can also be null or omitted for default options),
168 | * The second arg is the callback which sends object: response (more info below in README)
169 | */
170 | ImagePicker.showImagePicker(options, (response) => {
171 | console.log('Response = ', response);
172 |
173 | if (response.didCancel) {
174 | console.log('User cancelled image picker');
175 | }
176 | else if (response.error) {
177 | console.log('ImagePicker Error: ', response.error);
178 | }
179 | else if (response.customButton) {
180 | console.log('User tapped custom button: ', response.customButton);
181 | }
182 | else {
183 | let source = { uri: response.uri };
184 |
185 | // You can also display the image using data:
186 | // let source = { uri: 'data:image/jpeg;base64,' + response.data };
187 |
188 | this.setState({
189 | avatarSource: source
190 | });
191 | }
192 | });
193 | ```
194 | Then later, if you want to display this image in your render() method:
195 | ```javascript
196 |
197 | ```
198 |
199 | ### Directly Launching the Camera or Image Library
200 |
201 | To Launch the Camera or Image Library directly (skipping the alert dialog) you can
202 | do the following:
203 | ```javascript
204 | // Launch Camera:
205 | ImagePicker.launchCamera(options, (response) => {
206 | // Same code as in above section!
207 | });
208 |
209 | // Open Image Library:
210 | ImagePicker.launchImageLibrary(options, (response) => {
211 | // Same code as in above section!
212 | });
213 | ```
214 |
215 |
216 | #### Note
217 | On iOS, don't assume that the absolute uri returned will persist. See [#107](/../../issues/107)
218 |
219 | ### Options
220 |
221 | option | iOS | Android | Info
222 | ------ | ---- | ------- | ----
223 | title | OK | OK | Specify `null` or empty string to remove the title
224 | cancelButtonTitle | OK | OK | Specify `null` or empty string to remove this button (Android only)
225 | takePhotoButtonTitle | OK | OK | Specify `null` or empty string to remove this button
226 | chooseFromLibraryButtonTitle | OK | OK | Specify `null` or empty string to remove this button
227 | customButtons | OK | OK | An array containing objects with the name and title of buttons
228 | cameraType | OK | - | 'front' or 'back'
229 | mediaType | OK | OK | 'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android
230 | maxWidth | OK | OK | Photos only
231 | maxHeight | OK | OK | Photos only
232 | quality | OK | OK | 0 to 1, photos only
233 | videoQuality | OK | OK | 'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android
234 | durationLimit | OK | OK | Max video recording time, in seconds
235 | rotation | - | OK | Photos only, 0 to 360 degrees of rotation
236 | allowsEditing | OK | - | bool - enables built in iOS functionality to resize the image after selection
237 | noData | OK | OK | If true, disables the base64 `data` field from being generated (greatly improves performance on large photos)
238 | storageOptions | OK | OK | If this key is provided, the image will be saved in your app's `Documents` directory on iOS, or your app's `Pictures` directory on Android (rather than a temporary directory)
239 | storageOptions.skipBackup | OK | - | If true, the photo will NOT be backed up to iCloud
240 | storageOptions.path | OK | - | If set, will save the image at `Documents/[path]/` rather than the root `Documents`
241 | storageOptions.cameraRoll | OK | OK | If true, the cropped photo will be saved to the iOS Camera Roll or Android DCIM folder.
242 | storageOptions.waitUntilSaved | OK | - | If true, will delay the response callback until after the photo/video was saved to the Camera Roll. If the photo or video was just taken, then the file name and timestamp fields are only provided in the response object when this is true.
243 | permissionDenied.title | - | OK | Title of explaining permissions dialog. By default `Permission denied`.
244 | permissionDenied.text | - | OK | Message of explaining permissions dialog. By default `To be able to take pictures with your camera and choose images from your library.`.
245 | permissionDenied.reTryTitle | - | OK | Title of re-try button. By default `re-try`
246 | permissionDenied.okTitle | - | OK | Title of ok button. By default `I'm sure`
247 |
248 | ### The Response Object
249 |
250 | key | iOS | Android | Description
251 | ------ | ---- | ------- | ----------------------
252 | didCancel | OK | OK | Informs you if the user cancelled the process
253 | error | OK | OK | Contains an error message, if there is one
254 | customButton | OK | OK | If the user tapped one of your custom buttons, contains the name of it
255 | data | OK | OK | The base64 encoded image data (photos only)
256 | uri | OK | OK | The uri to the local file asset on the device (photo or video)
257 | origURL | OK | - | The URL of the original asset in photo library, if it exists
258 | isVertical | OK | OK | Will be true if the image is vertically oriented
259 | width | OK | OK | Image dimensions
260 | height | OK | OK | Image dimensions
261 | fileSize | OK | OK | The file size (photos only)
262 | type | - | OK | The file type (photos only)
263 | fileName | OK (photos and videos) | OK (photos) | The file name
264 | path | - | OK | The file path
265 | latitude | OK | OK | Latitude metadata, if available
266 | longitude | OK | OK | Longitude metadata, if available
267 | timestamp | OK | OK | Timestamp metadata, if available, in ISO8601 UTC format
268 | originalRotation | - | OK | Rotation degrees (photos only) *See [#109](/../../issues/199)*
269 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | import groovy.json.JsonSlurper
2 |
3 | def computeVersionName() {
4 | // dynamically retrieve version from package.json
5 | def slurper = new JsonSlurper()
6 | def json = slurper.parse(file('../package.json'), "utf-8")
7 | return json.version
8 | }
9 |
10 | buildscript {
11 | repositories {
12 | jcenter()
13 | }
14 |
15 | dependencies {
16 | classpath 'com.android.tools.build:gradle:2.2.+'
17 | }
18 | }
19 |
20 | apply plugin: 'com.android.library'
21 |
22 | android {
23 | compileSdkVersion 25
24 | buildToolsVersion "25.0.2"
25 |
26 | defaultConfig {
27 | minSdkVersion 16
28 | targetSdkVersion 25
29 | versionCode 1
30 | versionName computeVersionName()
31 | }
32 | lintOptions {
33 | abortOnError false
34 | }
35 | }
36 |
37 | repositories {
38 | mavenCentral()
39 | maven {
40 | url "$projectDir/../Example/node_modules/react-native/android"
41 | }
42 | maven {
43 | url "$projectDir/../../react-native/android"
44 | }
45 | }
46 |
47 | dependencies {
48 | compile "com.facebook.react:react-native:+" // From node_modules
49 |
50 | testCompile "junit:junit:4.10"
51 | testCompile "org.assertj:assertj-core:1.7.0"
52 | testCompile "org.robolectric:robolectric:3.3.2"
53 |
54 | testCompile "org.easytesting:fest-assert-core:${FEST_ASSERT_CORE_VERSION}"
55 | testCompile "org.powermock:powermock-api-mockito:${POWERMOCK_VERSION}"
56 | testCompile "org.powermock:powermock-module-junit4-rule:${POWERMOCK_VERSION}"
57 | testCompile "org.powermock:powermock-classloading-xstream:${POWERMOCK_VERSION}"
58 | testCompile "org.mockito:mockito-core:${MOCKITO_CORE_VERSION}"
59 | }
60 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | MOCKITO_CORE_VERSION=1.+
2 | POWERMOCK_VERSION=1.6.2
3 | FEST_ASSERT_CORE_VERSION=2.0M10
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weexext/weex-image-picker/5551532679937f9db2e50fef22296fc35dc2b4b6/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/ImagePickerModule.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.ActivityNotFoundException;
6 | import android.content.Context;
7 | import android.content.DialogInterface;
8 | import android.content.Intent;
9 | import android.graphics.BitmapFactory;
10 | import android.net.Uri;
11 | import android.provider.MediaStore;
12 | import android.provider.Settings;
13 | import android.support.annotation.NonNull;
14 | import android.support.annotation.Nullable;
15 | import android.support.annotation.StyleRes;
16 | import android.support.v4.app.ActivityCompat;
17 | import android.support.v7.app.AlertDialog;
18 | import android.text.TextUtils;
19 | import android.util.Base64;
20 | import android.util.Patterns;
21 | import android.webkit.MimeTypeMap;
22 | import android.content.pm.PackageManager;
23 |
24 | import com.facebook.react.ReactActivity;
25 | import com.facebook.react.bridge.ActivityEventListener;
26 | import com.facebook.react.bridge.Callback;
27 | import com.facebook.react.bridge.ReactApplicationContext;
28 | import com.facebook.react.bridge.ReactContextBaseJavaModule;
29 | import com.facebook.react.bridge.ReactMethod;
30 | import com.facebook.react.bridge.ReadableMap;
31 | import com.imagepicker.media.ImageConfig;
32 | import com.imagepicker.permissions.PermissionUtils;
33 | import com.imagepicker.permissions.OnImagePickerPermissionsCallback;
34 | import com.imagepicker.utils.MediaUtils.ReadExifResult;
35 | import com.imagepicker.utils.RealPathUtil;
36 | import com.imagepicker.utils.UI;
37 |
38 | import java.io.ByteArrayOutputStream;
39 | import java.io.File;
40 | import java.io.FileInputStream;
41 | import java.io.FileNotFoundException;
42 | import java.io.FileOutputStream;
43 | import java.io.IOException;
44 | import java.io.InputStream;
45 | import java.io.OutputStream;
46 | import java.lang.ref.WeakReference;
47 |
48 | import com.facebook.react.modules.core.PermissionListener;
49 |
50 | import static com.imagepicker.utils.MediaUtils.*;
51 | import static com.imagepicker.utils.MediaUtils.createNewFile;
52 | import static com.imagepicker.utils.MediaUtils.getResizedImage;
53 |
54 | public class ImagePickerModule extends ReactContextBaseJavaModule
55 | implements ActivityEventListener
56 | {
57 |
58 | public static final int REQUEST_LAUNCH_IMAGE_CAPTURE = 13001;
59 | public static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 13002;
60 | public static final int REQUEST_LAUNCH_VIDEO_LIBRARY = 13003;
61 | public static final int REQUEST_LAUNCH_VIDEO_CAPTURE = 13004;
62 | public static final int REQUEST_PERMISSIONS_FOR_CAMERA = 14001;
63 | public static final int REQUEST_PERMISSIONS_FOR_LIBRARY = 14002;
64 |
65 | private final ReactApplicationContext reactContext;
66 | private final int dialogThemeId;
67 |
68 | protected Callback callback;
69 | private ReadableMap options;
70 | protected Uri cameraCaptureURI;
71 | private Boolean noData = false;
72 | private Boolean pickVideo = false;
73 | private ImageConfig imageConfig = new ImageConfig(null, null, 0, 0, 100, 0, false);
74 |
75 | @Deprecated
76 | private int videoQuality = 1;
77 |
78 | @Deprecated
79 | private int videoDurationLimit = 0;
80 |
81 | private ResponseHelper responseHelper = new ResponseHelper();
82 | private PermissionListener listener = new PermissionListener()
83 | {
84 | public boolean onRequestPermissionsResult(final int requestCode,
85 | @NonNull final String[] permissions,
86 | @NonNull final int[] grantResults)
87 | {
88 | boolean permissionsGranted = true;
89 | for (int i = 0; i < permissions.length; i++)
90 | {
91 | final boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
92 | permissionsGranted = permissionsGranted && granted;
93 | }
94 |
95 | if (callback == null || options == null)
96 | {
97 | return false;
98 | }
99 |
100 | if (!permissionsGranted)
101 | {
102 | responseHelper.invokeError(callback, "Permissions weren't granted");
103 | return false;
104 | }
105 |
106 | switch (requestCode)
107 | {
108 | case REQUEST_PERMISSIONS_FOR_CAMERA:
109 | launchCamera(options, callback);
110 | break;
111 |
112 | case REQUEST_PERMISSIONS_FOR_LIBRARY:
113 | launchImageLibrary(options, callback);
114 | break;
115 |
116 | }
117 | return true;
118 | }
119 | };
120 |
121 | public ImagePickerModule(ReactApplicationContext reactContext,
122 | @StyleRes final int dialogThemeId)
123 | {
124 | super(reactContext);
125 |
126 | this.dialogThemeId = dialogThemeId;
127 | this.reactContext = reactContext;
128 | this.reactContext.addActivityEventListener(this);
129 | }
130 |
131 | @Override
132 | public String getName() {
133 | return "ImagePickerManager";
134 | }
135 |
136 | @ReactMethod
137 | public void showImagePicker(final ReadableMap options, final Callback callback) {
138 | Activity currentActivity = getCurrentActivity();
139 |
140 | if (currentActivity == null)
141 | {
142 | responseHelper.invokeError(callback, "can't find current Activity");
143 | return;
144 | }
145 |
146 | this.callback = callback;
147 | this.options = options;
148 | imageConfig = new ImageConfig(null, null, 0, 0, 100, 0, false);
149 |
150 | final AlertDialog dialog = UI.chooseDialog(this, options, new UI.OnAction()
151 | {
152 | @Override
153 | public void onTakePhoto(@NonNull final ImagePickerModule module)
154 | {
155 | if (module == null)
156 | {
157 | return;
158 | }
159 | module.launchCamera();
160 | }
161 |
162 | @Override
163 | public void onUseLibrary(@NonNull final ImagePickerModule module)
164 | {
165 | if (module == null)
166 | {
167 | return;
168 | }
169 | module.launchImageLibrary();
170 | }
171 |
172 | @Override
173 | public void onCancel(@NonNull final ImagePickerModule module)
174 | {
175 | if (module == null)
176 | {
177 | return;
178 | }
179 | module.doOnCancel();
180 | }
181 |
182 | @Override
183 | public void onCustomButton(@NonNull final ImagePickerModule module,
184 | @NonNull final String action)
185 | {
186 | if (module == null)
187 | {
188 | return;
189 | }
190 | module.invokeCustomButton(action);
191 | }
192 | });
193 | dialog.show();
194 | }
195 |
196 | public void doOnCancel()
197 | {
198 | responseHelper.invokeCancel(callback);
199 | }
200 |
201 | public void launchCamera()
202 | {
203 | this.launchCamera(this.options, this.callback);
204 | }
205 |
206 | // NOTE: Currently not reentrant / doesn't support concurrent requests
207 | @ReactMethod
208 | public void launchCamera(final ReadableMap options, final Callback callback)
209 | {
210 | if (!isCameraAvailable())
211 | {
212 | responseHelper.invokeError(callback, "Camera not available");
213 | return;
214 | }
215 |
216 | final Activity currentActivity = getCurrentActivity();
217 | if (currentActivity == null)
218 | {
219 | responseHelper.invokeError(callback, "can't find current Activity");
220 | return;
221 | }
222 |
223 | this.options = options;
224 |
225 | if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_CAMERA))
226 | {
227 | return;
228 | }
229 |
230 | parseOptions(this.options);
231 |
232 | int requestCode;
233 | Intent cameraIntent;
234 |
235 | if (pickVideo)
236 | {
237 | requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE;
238 | cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
239 | cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, videoQuality);
240 | if (videoDurationLimit > 0)
241 | {
242 | cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, videoDurationLimit);
243 | }
244 | }
245 | else
246 | {
247 | requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE;
248 | cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
249 |
250 | final File original = createNewFile(reactContext, this.options, false);
251 | imageConfig = imageConfig.withOriginalFile(original);
252 |
253 | cameraCaptureURI = RealPathUtil.compatUriFromFile(reactContext, imageConfig.original);
254 | if (cameraCaptureURI == null)
255 | {
256 | responseHelper.invokeError(callback, "Couldn't get file path for photo");
257 | return;
258 | }
259 | cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraCaptureURI);
260 | }
261 |
262 | if (cameraIntent.resolveActivity(reactContext.getPackageManager()) == null)
263 | {
264 | responseHelper.invokeError(callback, "Cannot launch camera");
265 | return;
266 | }
267 |
268 | this.callback = callback;
269 |
270 | try
271 | {
272 | currentActivity.startActivityForResult(cameraIntent, requestCode);
273 | }
274 | catch (ActivityNotFoundException e)
275 | {
276 | e.printStackTrace();
277 | responseHelper.invokeError(callback, "Cannot launch camera");
278 | }
279 | }
280 |
281 | public void launchImageLibrary()
282 | {
283 | this.launchImageLibrary(this.options, this.callback);
284 | }
285 | // NOTE: Currently not reentrant / doesn't support concurrent requests
286 | @ReactMethod
287 | public void launchImageLibrary(final ReadableMap options, final Callback callback)
288 | {
289 | final Activity currentActivity = getCurrentActivity();
290 | if (currentActivity == null) {
291 | responseHelper.invokeError(callback, "can't find current Activity");
292 | return;
293 | }
294 |
295 | this.options = options;
296 |
297 | if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_LIBRARY))
298 | {
299 | return;
300 | }
301 |
302 | parseOptions(this.options);
303 |
304 | int requestCode;
305 | Intent libraryIntent;
306 | if (pickVideo)
307 | {
308 | requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY;
309 | libraryIntent = new Intent(Intent.ACTION_PICK);
310 | libraryIntent.setType("video/*");
311 | }
312 | else
313 | {
314 | requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY;
315 | libraryIntent = new Intent(Intent.ACTION_PICK,
316 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
317 | }
318 |
319 | if (libraryIntent.resolveActivity(reactContext.getPackageManager()) == null)
320 | {
321 | responseHelper.invokeError(callback, "Cannot launch photo library");
322 | return;
323 | }
324 |
325 | this.callback = callback;
326 |
327 | try
328 | {
329 | currentActivity.startActivityForResult(libraryIntent, requestCode);
330 | }
331 | catch (ActivityNotFoundException e)
332 | {
333 | e.printStackTrace();
334 | responseHelper.invokeError(callback, "Cannot launch photo library");
335 | }
336 | }
337 |
338 | @Override
339 | public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
340 | //robustness code
341 | if (passResult(requestCode))
342 | {
343 | return;
344 | }
345 |
346 | responseHelper.cleanResponse();
347 |
348 | // user cancel
349 | if (resultCode != Activity.RESULT_OK)
350 | {
351 | removeUselessFiles(requestCode, imageConfig);
352 | responseHelper.invokeCancel(callback);
353 | callback = null;
354 | return;
355 | }
356 |
357 | Uri uri = null;
358 | switch (requestCode)
359 | {
360 | case REQUEST_LAUNCH_IMAGE_CAPTURE:
361 | uri = cameraCaptureURI;
362 | break;
363 |
364 | case REQUEST_LAUNCH_IMAGE_LIBRARY:
365 | uri = data.getData();
366 | String realPath = getRealPathFromURI(uri);
367 | final boolean isUrl = !TextUtils.isEmpty(realPath) &&
368 | Patterns.WEB_URL.matcher(realPath).matches();
369 | if (realPath == null || isUrl)
370 | {
371 | try
372 | {
373 | File file = createFileFromURI(uri);
374 | realPath = file.getAbsolutePath();
375 | uri = Uri.fromFile(file);
376 | }
377 | catch (Exception e)
378 | {
379 | // image not in cache
380 | responseHelper.putString("error", "Could not read photo");
381 | responseHelper.putString("uri", uri.toString());
382 | responseHelper.invokeResponse(callback);
383 | callback = null;
384 | return;
385 | }
386 | }
387 | imageConfig = imageConfig.withOriginalFile(new File(realPath));
388 | break;
389 |
390 | case REQUEST_LAUNCH_VIDEO_LIBRARY:
391 | responseHelper.putString("uri", data.getData().toString());
392 | responseHelper.putString("path", getRealPathFromURI(data.getData()));
393 | responseHelper.invokeResponse(callback);
394 | callback = null;
395 | return;
396 |
397 | case REQUEST_LAUNCH_VIDEO_CAPTURE:
398 | final String path = getRealPathFromURI(data.getData());
399 | responseHelper.putString("uri", data.getData().toString());
400 | responseHelper.putString("path", path);
401 | fileScan(reactContext, path);
402 | responseHelper.invokeResponse(callback);
403 | callback = null;
404 | return;
405 | }
406 |
407 | final ReadExifResult result = readExifInterface(responseHelper, imageConfig);
408 |
409 | if (result.error != null)
410 | {
411 | removeUselessFiles(requestCode, imageConfig);
412 | responseHelper.invokeError(callback, result.error.getMessage());
413 | callback = null;
414 | return;
415 | }
416 |
417 | BitmapFactory.Options options = new BitmapFactory.Options();
418 | options.inJustDecodeBounds = true;
419 | BitmapFactory.decodeFile(imageConfig.original.getAbsolutePath(), options);
420 | int initialWidth = options.outWidth;
421 | int initialHeight = options.outHeight;
422 | updatedResultResponse(uri, imageConfig.original.getAbsolutePath());
423 |
424 | // don't create a new file if contraint are respected
425 | if (imageConfig.useOriginal(initialWidth, initialHeight, result.currentRotation))
426 | {
427 | responseHelper.putInt("width", initialWidth);
428 | responseHelper.putInt("height", initialHeight);
429 | fileScan(reactContext, imageConfig.original.getAbsolutePath());
430 | }
431 | else
432 | {
433 | imageConfig = getResizedImage(reactContext, this.options, imageConfig, initialWidth, initialHeight, requestCode);
434 | if (imageConfig.resized == null)
435 | {
436 | removeUselessFiles(requestCode, imageConfig);
437 | responseHelper.putString("error", "Can't resize the image");
438 | }
439 | else
440 | {
441 | uri = Uri.fromFile(imageConfig.resized);
442 | BitmapFactory.decodeFile(imageConfig.resized.getAbsolutePath(), options);
443 | responseHelper.putInt("width", options.outWidth);
444 | responseHelper.putInt("height", options.outHeight);
445 |
446 | updatedResultResponse(uri, imageConfig.resized.getAbsolutePath());
447 | fileScan(reactContext, imageConfig.resized.getAbsolutePath());
448 | }
449 | }
450 |
451 | if (imageConfig.saveToCameraRoll && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE)
452 | {
453 | final RolloutPhotoResult rolloutResult = rolloutPhotoFromCamera(imageConfig);
454 |
455 | if (rolloutResult.error == null)
456 | {
457 | imageConfig = rolloutResult.imageConfig;
458 | uri = Uri.fromFile(imageConfig.getActualFile());
459 | updatedResultResponse(uri, imageConfig.getActualFile().getAbsolutePath());
460 | }
461 | else
462 | {
463 | removeUselessFiles(requestCode, imageConfig);
464 | final String errorMessage = new StringBuilder("Error moving image to camera roll: ")
465 | .append(rolloutResult.error.getMessage()).toString();
466 | responseHelper.putString("error", errorMessage);
467 | return;
468 | }
469 | }
470 |
471 | responseHelper.invokeResponse(callback);
472 | callback = null;
473 | this.options = null;
474 | }
475 |
476 | public void invokeCustomButton(@NonNull final String action)
477 | {
478 | responseHelper.invokeCustomButton(this.callback, action);
479 | }
480 |
481 | @Override
482 | public void onNewIntent(Intent intent) { }
483 |
484 | public Context getContext()
485 | {
486 | return getReactApplicationContext();
487 | }
488 |
489 | public @StyleRes int getDialogThemeId()
490 | {
491 | return this.dialogThemeId;
492 | }
493 |
494 | public @NonNull Activity getActivity()
495 | {
496 | return getCurrentActivity();
497 | }
498 |
499 |
500 | private boolean passResult(int requestCode)
501 | {
502 | return callback == null || (cameraCaptureURI == null && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE)
503 | || (requestCode != REQUEST_LAUNCH_IMAGE_CAPTURE && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY
504 | && requestCode != REQUEST_LAUNCH_VIDEO_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_CAPTURE);
505 | }
506 |
507 | private void updatedResultResponse(@Nullable final Uri uri,
508 | @NonNull final String path)
509 | {
510 | responseHelper.putString("uri", uri.toString());
511 | responseHelper.putString("path", path);
512 |
513 | if (!noData) {
514 | responseHelper.putString("data", getBase64StringFromFile(path));
515 | }
516 |
517 | putExtraFileInfo(path, responseHelper);
518 | }
519 |
520 | private boolean permissionsCheck(@NonNull final Activity activity,
521 | @NonNull final Callback callback,
522 | @NonNull final int requestCode)
523 | {
524 | final int writePermission = ActivityCompat
525 | .checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
526 | final int cameraPermission = ActivityCompat
527 | .checkSelfPermission(activity, Manifest.permission.CAMERA);
528 |
529 | final boolean permissionsGrated = writePermission == PackageManager.PERMISSION_GRANTED &&
530 | cameraPermission == PackageManager.PERMISSION_GRANTED;
531 |
532 | if (!permissionsGrated)
533 | {
534 | final Boolean dontAskAgain = ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) && ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA);
535 |
536 | if (dontAskAgain)
537 | {
538 | final AlertDialog dialog = PermissionUtils
539 | .explainingDialog(this, options, new PermissionUtils.OnExplainingPermissionCallback()
540 | {
541 | @Override
542 | public void onCancel(WeakReference moduleInstance,
543 | DialogInterface dialogInterface)
544 | {
545 | final ImagePickerModule module = moduleInstance.get();
546 | if (module == null)
547 | {
548 | return;
549 | }
550 | module.doOnCancel();
551 | }
552 |
553 | @Override
554 | public void onReTry(WeakReference moduleInstance,
555 | DialogInterface dialogInterface)
556 | {
557 | final ImagePickerModule module = moduleInstance.get();
558 | if (module == null)
559 | {
560 | return;
561 | }
562 | Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
563 | Uri uri = Uri.fromParts("package", module.getContext().getPackageName(), null);
564 | intent.setData(uri);
565 | final Activity innerActivity = module.getActivity();
566 | if (innerActivity == null)
567 | {
568 | return;
569 | }
570 | innerActivity.startActivityForResult(intent, 1);
571 | }
572 | });
573 | dialog.show();
574 | return false;
575 | }
576 | else
577 | {
578 | String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
579 | if (activity instanceof ReactActivity)
580 | {
581 | ((ReactActivity) activity).requestPermissions(PERMISSIONS, requestCode, listener);
582 | }
583 | else if (activity instanceof OnImagePickerPermissionsCallback)
584 | {
585 | ((OnImagePickerPermissionsCallback) activity).setPermissionListener(listener);
586 | ActivityCompat.requestPermissions(activity, PERMISSIONS, requestCode);
587 | }
588 | else
589 | {
590 | final String errorDescription = new StringBuilder(activity.getClass().getSimpleName())
591 | .append(" must implement ")
592 | .append(OnImagePickerPermissionsCallback.class.getSimpleName())
593 | .toString();
594 | throw new UnsupportedOperationException(errorDescription);
595 | }
596 | return false;
597 | }
598 | }
599 | return true;
600 | }
601 |
602 | private boolean isCameraAvailable() {
603 | return reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
604 | || reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
605 | }
606 |
607 | private @NonNull String getRealPathFromURI(@NonNull final Uri uri) {
608 | return RealPathUtil.getRealPathFromURI(reactContext, uri);
609 | }
610 |
611 | /**
612 | * Create a file from uri to allow image picking of image in disk cache
613 | * (Exemple: facebook image, google image etc..)
614 | *
615 | * @doc =>
616 | * https://github.com/nostra13/Android-Universal-Image-Loader#load--display-task-flow
617 | *
618 | * @param uri
619 | * @return File
620 | * @throws Exception
621 | */
622 | private File createFileFromURI(Uri uri) throws Exception {
623 | File file = new File(reactContext.getExternalCacheDir(), "photo-" + uri.getLastPathSegment());
624 | InputStream input = reactContext.getContentResolver().openInputStream(uri);
625 | OutputStream output = new FileOutputStream(file);
626 |
627 | try {
628 | byte[] buffer = new byte[4 * 1024];
629 | int read;
630 | while ((read = input.read(buffer)) != -1) {
631 | output.write(buffer, 0, read);
632 | }
633 | output.flush();
634 | } finally {
635 | output.close();
636 | input.close();
637 | }
638 |
639 | return file;
640 | }
641 |
642 | private String getBase64StringFromFile(String absoluteFilePath) {
643 | InputStream inputStream = null;
644 | try {
645 | inputStream = new FileInputStream(new File(absoluteFilePath));
646 | } catch (FileNotFoundException e) {
647 | e.printStackTrace();
648 | }
649 |
650 | byte[] bytes;
651 | byte[] buffer = new byte[8192];
652 | int bytesRead;
653 | ByteArrayOutputStream output = new ByteArrayOutputStream();
654 | try {
655 | while ((bytesRead = inputStream.read(buffer)) != -1) {
656 | output.write(buffer, 0, bytesRead);
657 | }
658 | } catch (IOException e) {
659 | e.printStackTrace();
660 | }
661 | bytes = output.toByteArray();
662 | return Base64.encodeToString(bytes, Base64.NO_WRAP);
663 | }
664 |
665 | private void putExtraFileInfo(@NonNull final String path,
666 | @NonNull final ResponseHelper responseHelper)
667 | {
668 | // size && filename
669 | try {
670 | File f = new File(path);
671 | responseHelper.putDouble("fileSize", f.length());
672 | responseHelper.putString("fileName", f.getName());
673 | } catch (Exception e) {
674 | e.printStackTrace();
675 | }
676 |
677 | // type
678 | String extension = MimeTypeMap.getFileExtensionFromUrl(path);
679 | if (extension != null) {
680 | responseHelper.putString("type", MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
681 | }
682 | }
683 |
684 | private void parseOptions(final ReadableMap options) {
685 | noData = false;
686 | if (options.hasKey("noData")) {
687 | noData = options.getBoolean("noData");
688 | }
689 | imageConfig = imageConfig.updateFromOptions(options);
690 | pickVideo = false;
691 | if (options.hasKey("mediaType") && options.getString("mediaType").equals("video")) {
692 | pickVideo = true;
693 | }
694 | videoQuality = 1;
695 | if (options.hasKey("videoQuality") && options.getString("videoQuality").equals("low")) {
696 | videoQuality = 0;
697 | }
698 | videoDurationLimit = 0;
699 | if (options.hasKey("durationLimit")) {
700 | videoDurationLimit = options.getInt("durationLimit");
701 | }
702 | }
703 | }
704 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/ImagePickerPackage.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker;
2 |
3 | import android.support.annotation.StyleRes;
4 |
5 | import com.facebook.react.ReactPackage;
6 | import com.facebook.react.bridge.JavaScriptModule;
7 | import com.facebook.react.bridge.NativeModule;
8 | import com.facebook.react.bridge.ReactApplicationContext;
9 | import com.facebook.react.uimanager.ViewManager;
10 |
11 | import java.util.Arrays;
12 | import java.util.Collections;
13 | import java.util.List;
14 |
15 | public class ImagePickerPackage implements ReactPackage {
16 | public static final int DEFAULT_EXPLAINING_PERMISSION_DIALIOG_THEME = R.style.DefaultExplainingPermissionsTheme;
17 | private @StyleRes final int dialogThemeId;
18 |
19 | public ImagePickerPackage()
20 | {
21 | this.dialogThemeId = DEFAULT_EXPLAINING_PERMISSION_DIALIOG_THEME;
22 | }
23 |
24 | public ImagePickerPackage(@StyleRes final int dialogThemeId)
25 | {
26 | this.dialogThemeId = dialogThemeId;
27 | }
28 |
29 | @Override
30 | public List createNativeModules(ReactApplicationContext reactContext) {
31 | return Arrays.asList(new ImagePickerModule(reactContext, dialogThemeId));
32 | }
33 |
34 | // Deprecated RN 0.47
35 | public List> createJSModules() {
36 | return Collections.emptyList();
37 | }
38 |
39 | @Override
40 | public List createViewManagers(ReactApplicationContext reactContext) {
41 | return Collections.emptyList();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/ResponseHelper.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.facebook.react.bridge.Arguments;
6 | import com.facebook.react.bridge.Callback;
7 | import com.facebook.react.bridge.WritableMap;
8 |
9 | /**
10 | * Created by rusfearuth on 24.02.17.
11 | */
12 |
13 | public class ResponseHelper
14 | {
15 | private WritableMap response = Arguments.createMap();
16 |
17 | public void cleanResponse()
18 | {
19 | response = Arguments.createMap();
20 | }
21 |
22 | public @NonNull WritableMap getResponse()
23 | {
24 | return response;
25 | }
26 |
27 | public void putString(@NonNull final String key,
28 | @NonNull final String value)
29 | {
30 | response.putString(key, value);
31 | }
32 |
33 | public void putInt(@NonNull final String key,
34 | final int value)
35 | {
36 | response.putInt(key, value);
37 | }
38 |
39 | public void putBoolean(@NonNull final String key,
40 | final boolean value)
41 | {
42 | response.putBoolean(key, value);
43 | }
44 |
45 | public void putDouble(@NonNull final String key,
46 | final double value)
47 | {
48 | response.putDouble(key, value);
49 | }
50 |
51 | public void invokeCustomButton(@NonNull final Callback callback,
52 | @NonNull final String action)
53 | {
54 | cleanResponse();
55 | response.putString("customButton", action);
56 | invokeResponse(callback);
57 | }
58 |
59 | public void invokeCancel(@NonNull final Callback callback)
60 | {
61 | cleanResponse();
62 | response.putBoolean("didCancel", true);
63 | invokeResponse(callback);
64 | }
65 |
66 | public void invokeError(@NonNull final Callback callback,
67 | @NonNull final String error)
68 | {
69 | cleanResponse();
70 | response.putString("error", error);
71 | invokeResponse(callback);
72 | }
73 |
74 | public void invokeResponse(@NonNull final Callback callback)
75 | {
76 | callback.invoke(response);
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/media/ImageConfig.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.media;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.Nullable;
5 |
6 | import com.facebook.react.bridge.ReadableMap;
7 |
8 | import java.io.File;
9 |
10 | /**
11 | * Created by rusfearuth on 15.03.17.
12 | */
13 |
14 | public class ImageConfig
15 | {
16 | public @Nullable final File original;
17 | public @Nullable final File resized;
18 | public final int maxWidth;
19 | public final int maxHeight;
20 | public final int quality;
21 | public final int rotation;
22 | public final boolean saveToCameraRoll;
23 |
24 | public ImageConfig(@Nullable final File original,
25 | @Nullable final File resized,
26 | final int maxWidth,
27 | final int maxHeight,
28 | final int quality,
29 | final int rotation,
30 | final boolean saveToCameraRoll)
31 | {
32 | this.original = original;
33 | this.resized = resized;
34 | this.maxWidth = maxWidth;
35 | this.maxHeight = maxHeight;
36 | this.quality = quality;
37 | this.rotation = rotation;
38 | this.saveToCameraRoll = saveToCameraRoll;
39 | }
40 |
41 | public @NonNull ImageConfig withMaxWidth(final int maxWidth)
42 | {
43 | return new ImageConfig(
44 | this.original, this.resized, maxWidth,
45 | this.maxHeight, this.quality, this.rotation,
46 | this.saveToCameraRoll
47 | );
48 | }
49 |
50 | public @NonNull ImageConfig withMaxHeight(final int maxHeight)
51 | {
52 | return new ImageConfig(
53 | this.original, this.resized, this.maxWidth,
54 | maxHeight, this.quality, this.rotation,
55 | this.saveToCameraRoll
56 | );
57 |
58 | }
59 |
60 | public @NonNull ImageConfig withQuality(final int quality)
61 | {
62 | return new ImageConfig(
63 | this.original, this.resized, this.maxWidth,
64 | this.maxHeight, quality, this.rotation,
65 | this.saveToCameraRoll
66 | );
67 | }
68 |
69 | public @NonNull ImageConfig withRotation(final int rotation)
70 | {
71 | return new ImageConfig(
72 | this.original, this.resized, this.maxWidth,
73 | this.maxHeight, this.quality, rotation,
74 | this.saveToCameraRoll
75 | );
76 | }
77 |
78 | public @NonNull ImageConfig withOriginalFile(@Nullable final File original)
79 | {
80 | return new ImageConfig(
81 | original, this.resized, this.maxWidth,
82 | this.maxHeight, this.quality, this.rotation,
83 | this.saveToCameraRoll
84 | );
85 | }
86 |
87 | public @NonNull ImageConfig withResizedFile(@Nullable final File resized)
88 | {
89 | return new ImageConfig(
90 | this.original, resized, this.maxWidth,
91 | this.maxHeight, this.quality, this.rotation,
92 | this.saveToCameraRoll
93 | );
94 | }
95 |
96 | public @NonNull ImageConfig withSaveToCameraRoll(@Nullable final boolean saveToCameraRoll)
97 | {
98 | return new ImageConfig(
99 | this.original, this.resized, this.maxWidth,
100 | this.maxHeight, this.quality, this.rotation,
101 | saveToCameraRoll
102 | );
103 | }
104 |
105 | public @NonNull ImageConfig updateFromOptions(@NonNull final ReadableMap options)
106 | {
107 | int maxWidth = 0;
108 | if (options.hasKey("maxWidth"))
109 | {
110 | maxWidth = options.getInt("maxWidth");
111 | }
112 | int maxHeight = 0;
113 | if (options.hasKey("maxHeight"))
114 | {
115 | maxHeight = options.getInt("maxHeight");
116 | }
117 | int quality = 100;
118 | if (options.hasKey("quality"))
119 | {
120 | quality = (int) (options.getDouble("quality") * 100);
121 | }
122 | int rotation = 0;
123 | if (options.hasKey("rotation"))
124 | {
125 | rotation = options.getInt("rotation");
126 | }
127 | boolean saveToCameraRoll = false;
128 | if (options.hasKey("storageOptions"))
129 | {
130 | final ReadableMap storageOptions = options.getMap("storageOptions");
131 | if (storageOptions.hasKey("cameraRoll"))
132 | {
133 | saveToCameraRoll = storageOptions.getBoolean("cameraRoll");
134 | }
135 | }
136 | return new ImageConfig(this.original, this.resized, maxWidth, maxHeight, quality, rotation, saveToCameraRoll);
137 | }
138 |
139 | public boolean useOriginal(int initialWidth,
140 | int initialHeight,
141 | int currentRotation)
142 | {
143 | return ((initialWidth < maxWidth && maxWidth > 0) || maxWidth == 0) &&
144 | ((initialHeight < maxHeight && maxHeight > 0) || maxHeight == 0) &&
145 | quality == 100 && (rotation == 0 || currentRotation == rotation);
146 | }
147 |
148 | public File getActualFile()
149 | {
150 | return resized != null ? resized: original;
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/media/VideoConfig.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.media;
2 |
3 | /**
4 | * Created by rusfearuth on 16.03.17.
5 | */
6 |
7 | public class VideoConfig
8 | {
9 | }
10 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/permissions/OnImagePickerPermissionsCallback.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.permissions;
2 |
3 | import android.support.annotation.NonNull;
4 | import com.facebook.react.modules.core.PermissionListener;
5 |
6 | /**
7 | * Created by rusfearuth on 25.02.17.
8 | */
9 | public interface OnImagePickerPermissionsCallback
10 | {
11 | void setPermissionListener(@NonNull PermissionListener listener);
12 | }
13 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/permissions/PermissionUtils.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.permissions;
2 |
3 | import android.app.Activity;
4 | import android.content.DialogInterface;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Nullable;
7 | import android.support.v7.app.AlertDialog;
8 |
9 | import com.facebook.react.bridge.ReadableMap;
10 | import com.imagepicker.ImagePickerModule;
11 | import com.imagepicker.R;
12 |
13 | import java.lang.ref.WeakReference;
14 |
15 | /**
16 | * Created by rusfearuth on 03.03.17.
17 | */
18 |
19 | public class PermissionUtils
20 | {
21 | public static @Nullable AlertDialog explainingDialog(@NonNull final ImagePickerModule module,
22 | @NonNull final ReadableMap options,
23 | @NonNull final OnExplainingPermissionCallback callback)
24 | {
25 | if (module.getContext() == null)
26 | {
27 | return null;
28 | }
29 | final ReadableMap permissionDenied = options.getMap("permissionDenied");
30 | final String title = permissionDenied.getString("title");
31 | final String text = permissionDenied.getString("text");
32 | final String btnReTryTitle = permissionDenied.getString("reTryTitle");
33 | final String btnOkTitle = permissionDenied.getString("okTitle");
34 | final WeakReference reference = new WeakReference<>(module);
35 |
36 | final Activity activity = module.getActivity();
37 |
38 | if (activity == null)
39 | {
40 | return null;
41 | }
42 |
43 | AlertDialog.Builder builder = new AlertDialog.Builder(activity, module.getDialogThemeId());
44 | builder
45 | .setTitle(title)
46 | .setMessage(text)
47 | .setCancelable(false)
48 | .setNegativeButton(btnOkTitle, new DialogInterface.OnClickListener()
49 | {
50 | @Override
51 | public void onClick(final DialogInterface dialogInterface,
52 | int i)
53 | {
54 | callback.onCancel(reference, dialogInterface);
55 | }
56 | })
57 | .setPositiveButton(btnReTryTitle, new DialogInterface.OnClickListener()
58 | {
59 | @Override
60 | public void onClick(DialogInterface dialogInterface,
61 | int i)
62 | {
63 | callback.onReTry(reference, dialogInterface);
64 | }
65 | });
66 |
67 | return builder.create();
68 | }
69 |
70 | public interface OnExplainingPermissionCallback {
71 | void onCancel(WeakReference moduleInstance, DialogInterface dialogInterface);
72 | void onReTry(WeakReference moduleInstance, DialogInterface dialogInterface);
73 | }
74 | }
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/permissions/PermissionsHelper.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.permissions;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | /**
6 | * Created by rusfearuth on 03.03.17.
7 | */
8 |
9 | public class PermissionsHelper
10 | {
11 | }
12 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/utils/ButtonsHelper.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.utils;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.Nullable;
5 |
6 | import com.facebook.react.bridge.ReadableArray;
7 | import com.facebook.react.bridge.ReadableMap;
8 |
9 | import java.util.LinkedList;
10 | import java.util.List;
11 |
12 |
13 | /**
14 | * Created by rusfearuth on 20.02.17.
15 | */
16 |
17 | public class ButtonsHelper
18 | {
19 | public static class Item
20 | {
21 | public final String title;
22 | public final String action;
23 |
24 | public Item(@NonNull final String title,
25 | @NonNull final String action)
26 | {
27 | this.title = title;
28 | this.action = action;
29 | }
30 | }
31 |
32 | public final @Nullable Item btnCamera;
33 | public final @Nullable Item btnLibrary;
34 | public final @Nullable Item btnCancel;
35 | public final List- customButtons;
36 |
37 | public ButtonsHelper(@Nullable final Item btnCamera,
38 | @Nullable final Item btnLibrary,
39 | @Nullable final Item btnCancel,
40 | @NonNull final LinkedList
- customButtons)
41 | {
42 | this.btnCamera = btnCamera;
43 | this.btnLibrary = btnLibrary;
44 | this.btnCancel = btnCancel;
45 | this.customButtons = customButtons;
46 | }
47 |
48 | public List getTitles()
49 | {
50 | List result = new LinkedList<>();
51 |
52 | if (btnCamera != null)
53 | {
54 | result.add(btnCamera.title);
55 | }
56 |
57 | if (btnLibrary != null)
58 | {
59 | result.add(btnLibrary.title);
60 | }
61 |
62 | for (int i = 0; i < customButtons.size(); i++)
63 | {
64 | result.add(customButtons.get(i).title);
65 | }
66 |
67 | return result;
68 | }
69 |
70 | public List getActions()
71 | {
72 | List result = new LinkedList<>();
73 |
74 | if (btnCamera != null)
75 | {
76 | result.add(btnCamera.action);
77 | }
78 |
79 | if (btnLibrary != null)
80 | {
81 | result.add(btnLibrary.action);
82 | }
83 |
84 | for (int i = 0; i < customButtons.size(); i++)
85 | {
86 | result.add(customButtons.get(i).action);
87 | }
88 |
89 | return result;
90 | }
91 |
92 | public static ButtonsHelper newInstance(@NonNull final ReadableMap options)
93 | {
94 | Item btnCamera = getItemFromOption(options, "takePhotoButtonTitle", "photo");
95 | Item btnLibrary = getItemFromOption(options, "chooseFromLibraryButtonTitle", "library");
96 | Item btnCancel = getItemFromOption(options, "cancelButtonTitle", "cancel");
97 | LinkedList
- customButtons = getCustomButtons(options);
98 |
99 | return new ButtonsHelper(btnCamera, btnLibrary, btnCancel, customButtons);
100 | }
101 |
102 | private static @Nullable Item getItemFromOption(@NonNull final ReadableMap options,
103 | @NonNull final String key,
104 | @NonNull final String action)
105 | {
106 | if (!ReadableMapUtils.hasAndNotEmptyString(options, key))
107 | {
108 | return null;
109 | }
110 |
111 | final String title = options.getString(key);
112 |
113 | return new Item(title, action);
114 | }
115 |
116 | private static @NonNull LinkedList
- getCustomButtons(@NonNull final ReadableMap options)
117 | {
118 | LinkedList
- result = new LinkedList<>();
119 | if (!options.hasKey("customButtons"))
120 | {
121 | return result;
122 | }
123 |
124 | final ReadableArray customButtons = options.getArray("customButtons");
125 | for (int i = 0; i < customButtons.size(); i++)
126 | {
127 | final ReadableMap button = customButtons.getMap(i);
128 | final String title = button.getString("title");
129 | final String action = button.getString("name");
130 | result.add(new Item(title, action));
131 | }
132 |
133 | return result;
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/utils/MediaUtils.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.utils;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.BitmapFactory;
6 | import android.graphics.Matrix;
7 | import android.media.ExifInterface;
8 | import android.media.MediaScannerConnection;
9 | import android.net.Uri;
10 | import android.os.Environment;
11 | import android.support.annotation.NonNull;
12 | import android.support.annotation.Nullable;
13 | import android.util.Log;
14 |
15 | import com.facebook.react.bridge.ReadableMap;
16 | import com.imagepicker.ImagePickerModule;
17 | import com.imagepicker.ResponseHelper;
18 | import com.imagepicker.media.ImageConfig;
19 |
20 | import java.io.ByteArrayOutputStream;
21 | import java.io.File;
22 | import java.io.FileInputStream;
23 | import java.io.FileNotFoundException;
24 | import java.io.FileOutputStream;
25 | import java.io.IOException;
26 | import java.nio.channels.FileChannel;
27 | import java.text.DateFormat;
28 | import java.text.SimpleDateFormat;
29 | import java.util.TimeZone;
30 | import java.util.UUID;
31 |
32 | import static com.imagepicker.ImagePickerModule.REQUEST_LAUNCH_IMAGE_CAPTURE;
33 |
34 | /**
35 | * Created by rusfearuth on 15.03.17.
36 | */
37 |
38 | public class MediaUtils
39 | {
40 | public static @Nullable File createNewFile(@NonNull final Context reactContext,
41 | @NonNull final ReadableMap options,
42 | @NonNull final boolean forceLocal)
43 | {
44 | final String filename = new StringBuilder("image-")
45 | .append(UUID.randomUUID().toString())
46 | .append(".jpg")
47 | .toString();
48 |
49 | final File path = ReadableMapUtils.hasAndNotNullReadableMap(options, "storageOptions") && !forceLocal
50 | ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
51 | : reactContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
52 |
53 | File result = new File(path, filename);
54 |
55 | try
56 | {
57 | path.mkdirs();
58 | result.createNewFile();
59 | }
60 | catch (IOException e)
61 | {
62 | e.printStackTrace();
63 | result = null;
64 | }
65 |
66 | return result;
67 | }
68 |
69 | /**
70 | * Create a resized image to fulfill the maxWidth/maxHeight, quality and rotation values
71 | *
72 | * @param context
73 | * @param options
74 | * @param imageConfig
75 | * @param initialWidth
76 | * @param initialHeight
77 | * @return updated ImageConfig
78 | */
79 | public static @NonNull ImageConfig getResizedImage(@NonNull final Context context,
80 | @NonNull final ReadableMap options,
81 | @NonNull final ImageConfig imageConfig,
82 | int initialWidth,
83 | int initialHeight,
84 | final int requestCode)
85 | {
86 | BitmapFactory.Options imageOptions = new BitmapFactory.Options();
87 | imageOptions.inScaled = false;
88 | imageOptions.inSampleSize = 1;
89 |
90 | if (imageConfig.maxWidth != 0 || imageConfig.maxHeight != 0) {
91 | while ((imageConfig.maxWidth == 0 || initialWidth > 2 * imageConfig.maxWidth) &&
92 | (imageConfig.maxHeight == 0 || initialHeight > 2 * imageConfig.maxHeight)) {
93 | imageOptions.inSampleSize *= 2;
94 | initialHeight /= 2;
95 | initialWidth /= 2;
96 | }
97 | }
98 |
99 | Bitmap photo = BitmapFactory.decodeFile(imageConfig.original.getAbsolutePath(), imageOptions);
100 |
101 | if (photo == null)
102 | {
103 | return null;
104 | }
105 |
106 | ImageConfig result = imageConfig;
107 |
108 | Bitmap scaledPhoto = null;
109 | if (imageConfig.maxWidth == 0 || imageConfig.maxWidth > initialWidth)
110 | {
111 | result = result.withMaxWidth(initialWidth);
112 | }
113 | if (imageConfig.maxHeight == 0 || imageConfig.maxWidth > initialHeight)
114 | {
115 | result = result.withMaxHeight(initialHeight);
116 | }
117 |
118 | double widthRatio = (double) result.maxWidth / initialWidth;
119 | double heightRatio = (double) result.maxHeight / initialHeight;
120 |
121 | double ratio = (widthRatio < heightRatio)
122 | ? widthRatio
123 | : heightRatio;
124 |
125 | Matrix matrix = new Matrix();
126 | matrix.postRotate(result.rotation);
127 | matrix.postScale((float) ratio, (float) ratio);
128 |
129 | ExifInterface exif;
130 | try
131 | {
132 | exif = new ExifInterface(result.original.getAbsolutePath());
133 |
134 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
135 |
136 | switch (orientation)
137 | {
138 | case 6:
139 | matrix.postRotate(90);
140 | break;
141 | case 3:
142 | matrix.postRotate(180);
143 | break;
144 | case 8:
145 | matrix.postRotate(270);
146 | break;
147 | }
148 | }
149 | catch (IOException e)
150 | {
151 | e.printStackTrace();
152 | }
153 |
154 | scaledPhoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
155 | ByteArrayOutputStream bytes = new ByteArrayOutputStream();
156 | scaledPhoto.compress(Bitmap.CompressFormat.JPEG, result.quality, bytes);
157 |
158 | final boolean forceLocal = requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE;
159 | final File resized = createNewFile(context, options, !forceLocal);
160 |
161 | if (resized == null)
162 | {
163 | if (photo != null)
164 | {
165 | photo.recycle();
166 | photo = null;
167 | }
168 | if (scaledPhoto != null)
169 | {
170 | scaledPhoto.recycle();
171 | scaledPhoto = null;
172 | }
173 | return imageConfig;
174 | }
175 |
176 | result = result.withResizedFile(resized);
177 |
178 | FileOutputStream fos;
179 | try
180 | {
181 | fos = new FileOutputStream(result.resized);
182 | fos.write(bytes.toByteArray());
183 | }
184 | catch (IOException e)
185 | {
186 | e.printStackTrace();
187 | }
188 |
189 | if (photo != null)
190 | {
191 | photo.recycle();
192 | photo = null;
193 | }
194 | if (scaledPhoto != null)
195 | {
196 | scaledPhoto.recycle();
197 | scaledPhoto = null;
198 | }
199 | return result;
200 | }
201 |
202 | public static void removeUselessFiles(final int requestCode,
203 | @NonNull final ImageConfig imageConfig)
204 | {
205 | if (requestCode != ImagePickerModule.REQUEST_LAUNCH_IMAGE_CAPTURE)
206 | {
207 | return;
208 | }
209 |
210 | if (imageConfig.original != null && imageConfig.original.exists())
211 | {
212 | imageConfig.original.delete();
213 | }
214 |
215 | if (imageConfig.resized != null && imageConfig.resized.exists())
216 | {
217 | imageConfig.resized.delete();
218 | }
219 | }
220 |
221 | public static void fileScan(@Nullable final Context reactContext,
222 | @NonNull final String path)
223 | {
224 | if (reactContext == null)
225 | {
226 | return;
227 | }
228 | MediaScannerConnection.scanFile(reactContext,
229 | new String[] { path }, null,
230 | new MediaScannerConnection.OnScanCompletedListener()
231 | {
232 | public void onScanCompleted(String path, Uri uri)
233 | {
234 | Log.i("TAG", new StringBuilder("Finished scanning ").append(path).toString());
235 | }
236 | });
237 | }
238 |
239 | public static ReadExifResult readExifInterface(@NonNull ResponseHelper responseHelper,
240 | @NonNull final ImageConfig imageConfig)
241 | {
242 | ReadExifResult result;
243 | int currentRotation = 0;
244 |
245 | try
246 | {
247 | ExifInterface exif = new ExifInterface(imageConfig.original.getAbsolutePath());
248 |
249 | // extract lat, long, and timestamp and add to the response
250 | float[] latlng = new float[2];
251 | exif.getLatLong(latlng);
252 | float latitude = latlng[0];
253 | float longitude = latlng[1];
254 | if(latitude != 0f || longitude != 0f)
255 | {
256 | responseHelper.putDouble("latitude", latitude);
257 | responseHelper.putDouble("longitude", longitude);
258 | }
259 |
260 | final String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME);
261 | final SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
262 |
263 | final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
264 | isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
265 |
266 | try
267 | {
268 | final String isoFormatString = new StringBuilder(isoFormat.format(exifDatetimeFormat.parse(timestamp)))
269 | .append("Z").toString();
270 | responseHelper.putString("timestamp", isoFormatString);
271 | }
272 | catch (Exception e) {}
273 |
274 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
275 | boolean isVertical = true;
276 | switch (orientation) {
277 | case ExifInterface.ORIENTATION_ROTATE_270:
278 | isVertical = false;
279 | currentRotation = 270;
280 | break;
281 | case ExifInterface.ORIENTATION_ROTATE_90:
282 | isVertical = false;
283 | currentRotation = 90;
284 | break;
285 | case ExifInterface.ORIENTATION_ROTATE_180:
286 | currentRotation = 180;
287 | break;
288 | }
289 | responseHelper.putInt("originalRotation", currentRotation);
290 | responseHelper.putBoolean("isVertical", isVertical);
291 | result = new ReadExifResult(currentRotation, null);
292 | }
293 | catch (IOException e)
294 | {
295 | e.printStackTrace();
296 | result = new ReadExifResult(currentRotation, e);
297 | }
298 |
299 | return result;
300 | }
301 |
302 | public static @Nullable RolloutPhotoResult rolloutPhotoFromCamera(@NonNull final ImageConfig imageConfig)
303 | {
304 | RolloutPhotoResult result = null;
305 | final File oldFile = imageConfig.resized == null ? imageConfig.original: imageConfig.resized;
306 | final File newDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
307 | final File newFile = new File(newDir.getPath(), oldFile.getName());
308 |
309 | try
310 | {
311 | moveFile(oldFile, newFile);
312 | ImageConfig newImageConfig;
313 | if (imageConfig.resized != null)
314 | {
315 | newImageConfig = imageConfig.withResizedFile(newFile);
316 | }
317 | else
318 | {
319 | newImageConfig = imageConfig.withOriginalFile(newFile);
320 | }
321 | result = new RolloutPhotoResult(newImageConfig, null);
322 | }
323 | catch (IOException e)
324 | {
325 | e.printStackTrace();
326 | result = new RolloutPhotoResult(imageConfig, e);
327 | }
328 | return result;
329 | }
330 |
331 | /**
332 | * Move a file from one location to another.
333 | *
334 | * This is done via copy + deletion, because Android will throw an error
335 | * if you try to move a file across mount points, e.g. to the SD card.
336 | */
337 | private static void moveFile(@NonNull final File oldFile,
338 | @NonNull final File newFile) throws IOException
339 | {
340 | FileChannel oldChannel = null;
341 | FileChannel newChannel = null;
342 |
343 | try
344 | {
345 | oldChannel = new FileInputStream(oldFile).getChannel();
346 | newChannel = new FileOutputStream(newFile).getChannel();
347 | oldChannel.transferTo(0, oldChannel.size(), newChannel);
348 |
349 | oldFile.delete();
350 | }
351 | finally
352 | {
353 | try
354 | {
355 | if (oldChannel != null) oldChannel.close();
356 | if (newChannel != null) newChannel.close();
357 | }
358 | catch (IOException e)
359 | {
360 | e.printStackTrace();
361 | }
362 | }
363 | }
364 |
365 |
366 | public static class RolloutPhotoResult
367 | {
368 | public final ImageConfig imageConfig;
369 | public final Throwable error;
370 |
371 | public RolloutPhotoResult(@NonNull final ImageConfig imageConfig,
372 | @Nullable final Throwable error)
373 | {
374 | this.imageConfig = imageConfig;
375 | this.error = error;
376 | }
377 | }
378 |
379 |
380 | public static class ReadExifResult
381 | {
382 | public final int currentRotation;
383 | public final Throwable error;
384 |
385 | public ReadExifResult(int currentRotation,
386 | @Nullable final Throwable error)
387 | {
388 | this.currentRotation = currentRotation;
389 | this.error = error;
390 | }
391 | }
392 | }
393 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/utils/ReadableMapUtils.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.utils;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.text.TextUtils;
5 |
6 | import com.facebook.react.bridge.ReadableMap;
7 |
8 | /**
9 | * Created by rusfearuth on 22.02.17.
10 | */
11 |
12 | public class ReadableMapUtils
13 | {
14 | public static @NonNull boolean hasAndNotEmpty(@NonNull Class clazz,
15 | @NonNull final ReadableMap target,
16 | @NonNull final String key)
17 | {
18 | if (!target.hasKey(key))
19 | {
20 | return false;
21 | }
22 |
23 | if (target.isNull(key))
24 | {
25 | return false;
26 | }
27 |
28 | if (String.class.equals(clazz))
29 | {
30 | final String value = target.getString(key);
31 | return !TextUtils.isEmpty(value);
32 | }
33 |
34 | return true;
35 | }
36 |
37 |
38 | public static @NonNull boolean hasAndNotNullReadableMap(@NonNull final ReadableMap target,
39 | @NonNull final String key)
40 | {
41 | return hasAndNotEmpty(ReadableMap.class, target, key);
42 | }
43 |
44 |
45 |
46 | public static @NonNull boolean hasAndNotEmptyString(@NonNull final ReadableMap target,
47 | @NonNull final String key)
48 | {
49 | return hasAndNotEmpty(String.class, target, key);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/utils/RealPathUtil.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.utils;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.annotation.TargetApi;
5 | import android.content.Context;
6 | import android.database.Cursor;
7 | import android.net.Uri;
8 | import android.os.Build;
9 | import android.provider.DocumentsContract;
10 | import android.provider.MediaStore;
11 | import android.content.ContentUris;
12 | import android.os.Environment;
13 | import android.support.annotation.NonNull;
14 | import android.support.annotation.Nullable;
15 | import android.support.v4.content.FileProvider;
16 |
17 | import java.io.File;
18 |
19 | public class RealPathUtil {
20 |
21 | public static @Nullable Uri compatUriFromFile(@NonNull final Context context,
22 | @NonNull final File file) {
23 | Uri result = null;
24 | if (Build.VERSION.SDK_INT < 21) {
25 | result = Uri.fromFile(file);
26 | }
27 | else {
28 | final String packageName = context.getApplicationContext().getPackageName();
29 | final String authority = new StringBuilder(packageName).append(".provider").toString();
30 | try {
31 | result = FileProvider.getUriForFile(context, authority, file);
32 | }
33 | catch(IllegalArgumentException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 | return result;
38 | }
39 |
40 | @SuppressLint("NewApi")
41 | public static @Nullable String getRealPathFromURI(@NonNull final Context context,
42 | @NonNull final Uri uri) {
43 |
44 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
45 |
46 | // DocumentProvider
47 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
48 | // ExternalStorageProvider
49 | if (isExternalStorageDocument(uri)) {
50 | final String docId = DocumentsContract.getDocumentId(uri);
51 | final String[] split = docId.split(":");
52 | final String type = split[0];
53 |
54 | if ("primary".equalsIgnoreCase(type)) {
55 | return Environment.getExternalStorageDirectory() + "/" + split[1];
56 | }
57 |
58 | // TODO handle non-primary volumes
59 | }
60 | // DownloadsProvider
61 | else if (isDownloadsDocument(uri)) {
62 |
63 | final String id = DocumentsContract.getDocumentId(uri);
64 | final Uri contentUri = ContentUris.withAppendedId(
65 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
66 |
67 | return getDataColumn(context, contentUri, null, null);
68 | }
69 | // MediaProvider
70 | else if (isMediaDocument(uri)) {
71 | final String docId = DocumentsContract.getDocumentId(uri);
72 | final String[] split = docId.split(":");
73 | final String type = split[0];
74 |
75 | Uri contentUri = null;
76 | if ("image".equals(type)) {
77 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
78 | } else if ("video".equals(type)) {
79 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
80 | } else if ("audio".equals(type)) {
81 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
82 | }
83 |
84 | final String selection = "_id=?";
85 | final String[] selectionArgs = new String[] {
86 | split[1]
87 | };
88 |
89 | return getDataColumn(context, contentUri, selection, selectionArgs);
90 | }
91 | }
92 | // MediaStore (and general)
93 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
94 |
95 | // Return the remote address
96 | if (isGooglePhotosUri(uri))
97 | return uri.getLastPathSegment();
98 |
99 | if (isFileProviderUri(context, uri))
100 | return getFileProviderPath(context, uri);
101 |
102 | return getDataColumn(context, uri, null, null);
103 | }
104 | // File
105 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
106 | return uri.getPath();
107 | }
108 |
109 | return null;
110 | }
111 |
112 | /**
113 | * Get the value of the data column for this Uri. This is useful for
114 | * MediaStore Uris, and other file-based ContentProviders.
115 | *
116 | * @param context The context.
117 | * @param uri The Uri to query.
118 | * @param selection (Optional) Filter used in the query.
119 | * @param selectionArgs (Optional) Selection arguments used in the query.
120 | * @return The value of the _data column, which is typically a file path.
121 | */
122 | public static String getDataColumn(Context context, Uri uri, String selection,
123 | String[] selectionArgs) {
124 |
125 | Cursor cursor = null;
126 | final String column = "_data";
127 | final String[] projection = {
128 | column
129 | };
130 |
131 | try {
132 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
133 | null);
134 | if (cursor != null && cursor.moveToFirst()) {
135 | final int index = cursor.getColumnIndexOrThrow(column);
136 | return cursor.getString(index);
137 | }
138 | } finally {
139 | if (cursor != null)
140 | cursor.close();
141 | }
142 | return null;
143 | }
144 |
145 |
146 | /**
147 | * @param uri The Uri to check.
148 | * @return Whether the Uri authority is ExternalStorageProvider.
149 | */
150 | public static boolean isExternalStorageDocument(Uri uri) {
151 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
152 | }
153 |
154 | /**
155 | * @param uri The Uri to check.
156 | * @return Whether the Uri authority is DownloadsProvider.
157 | */
158 | public static boolean isDownloadsDocument(Uri uri) {
159 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
160 | }
161 |
162 | /**
163 | * @param uri The Uri to check.
164 | * @return Whether the Uri authority is MediaProvider.
165 | */
166 | public static boolean isMediaDocument(Uri uri) {
167 | return "com.android.providers.media.documents".equals(uri.getAuthority());
168 | }
169 |
170 | /**
171 | * @param uri The Uri to check.
172 | * @return Whether the Uri authority is Google Photos.
173 | */
174 | public static boolean isGooglePhotosUri(@NonNull final Uri uri) {
175 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
176 | }
177 |
178 | /**
179 | * @param context The Application context
180 | * @param uri The Uri is checked by functions
181 | * @return Whether the Uri authority is FileProvider
182 | */
183 | public static boolean isFileProviderUri(@NonNull final Context context,
184 | @NonNull final Uri uri) {
185 | final String packageName = context.getPackageName();
186 | final String authority = new StringBuilder(packageName).append(".provider").toString();
187 | return authority.equals(uri.getAuthority());
188 | }
189 |
190 | /**
191 | * @param context The Application context
192 | * @param uri The Uri is checked by functions
193 | * @return File path or null if file is missing
194 | */
195 | public static @Nullable String getFileProviderPath(@NonNull final Context context,
196 | @NonNull final Uri uri)
197 | {
198 | final File appDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
199 | final File file = new File(appDir, uri.getLastPathSegment());
200 | return file.exists() ? file.toString(): null;
201 | }
202 | }
--------------------------------------------------------------------------------
/android/src/main/java/com/imagepicker/utils/UI.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.utils;
2 |
3 | import android.content.Context;
4 | import android.content.DialogInterface;
5 | import android.graphics.drawable.ColorDrawable;
6 | import android.support.annotation.NonNull;
7 | import android.support.annotation.Nullable;
8 | import android.support.v7.app.AlertDialog;
9 | import android.widget.ArrayAdapter;
10 |
11 | import com.facebook.react.bridge.ReadableMap;
12 | import com.imagepicker.ImagePickerModule;
13 | import com.imagepicker.R;
14 |
15 | import java.lang.ref.WeakReference;
16 | import java.util.List;
17 |
18 | /**
19 | * @author Alexander Ustinov
20 | */
21 | public class UI
22 | {
23 | public static @NonNull AlertDialog chooseDialog(@Nullable final ImagePickerModule module,
24 | @NonNull final ReadableMap options,
25 | @Nullable final OnAction callback)
26 | {
27 | final Context context = module.getActivity();
28 | if (context == null)
29 | {
30 | return null;
31 | }
32 | final WeakReference reference = new WeakReference<>(module);
33 |
34 | final ButtonsHelper buttons = ButtonsHelper.newInstance(options);
35 | final List titles = buttons.getTitles();
36 | final List actions = buttons.getActions();
37 | ArrayAdapter adapter = new ArrayAdapter<>(
38 | context,
39 | R.layout.list_item,
40 | titles
41 | );
42 | AlertDialog.Builder builder = new AlertDialog.Builder(context, module.getDialogThemeId() /*android.R.style.Theme_Holo_Light_Dialog*/);
43 | if (ReadableMapUtils.hasAndNotEmptyString(options, "title"))
44 | {
45 | builder.setTitle(options.getString("title"));
46 | }
47 |
48 | builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
49 | public void onClick(DialogInterface dialog, int index) {
50 | final String action = actions.get(index);
51 |
52 | switch (action) {
53 | case "photo":
54 | callback.onTakePhoto(reference.get());
55 | break;
56 |
57 | case "library":
58 | callback.onUseLibrary(reference.get());
59 | break;
60 |
61 | case "cancel":
62 | callback.onCancel(reference.get());
63 | break;
64 |
65 | default:
66 | callback.onCustomButton(reference.get(), action);
67 | }
68 | }
69 | });
70 |
71 | builder.setNegativeButton(buttons.btnCancel.title, new DialogInterface.OnClickListener()
72 | {
73 | @Override
74 | public void onClick(DialogInterface dialogInterface,
75 | int i)
76 | {
77 | callback.onCancel(reference.get());
78 | dialogInterface.dismiss();
79 | }
80 | });
81 |
82 | final AlertDialog dialog = builder.create();
83 |
84 | dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
85 | {
86 | @Override
87 | public void onCancel(@NonNull final DialogInterface dialog)
88 | {
89 | callback.onCancel(reference.get());
90 | dialog.dismiss();
91 | }
92 | });
93 |
94 | //dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
95 | return dialog;
96 | }
97 |
98 | public interface OnAction
99 | {
100 | void onTakePhoto(@Nullable ImagePickerModule module);
101 | void onUseLibrary(@Nullable ImagePickerModule module);
102 | void onCancel(@Nullable ImagePickerModule module);
103 | void onCustomButton(@Nullable ImagePickerModule module, String action);
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/android/src/main/res/layout/list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/android/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 |
--------------------------------------------------------------------------------
/android/src/main/res/xml/provider_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/android/src/test/java/com/imagepicker/testing/ImagePickerModuleTest.java:
--------------------------------------------------------------------------------
1 | package com.imagepicker.testing;
2 |
3 | import android.app.Activity;
4 | import android.content.pm.PackageManager;
5 | import android.net.Uri;
6 |
7 | import com.facebook.react.bridge.Arguments;
8 | import com.facebook.react.bridge.Callback;
9 | import com.facebook.react.bridge.JavaOnlyArray;
10 | import com.facebook.react.bridge.JavaOnlyMap;
11 | import com.facebook.react.bridge.ReactApplicationContext;
12 | import com.facebook.react.common.build.ReactBuildConfig;
13 | import com.imagepicker.ImagePickerModule;
14 | import com.imagepicker.R;
15 |
16 | import org.junit.After;
17 | import org.junit.Before;
18 | import org.junit.Rule;
19 | import org.junit.Test;
20 | import org.junit.runner.RunWith;
21 | import org.mockito.invocation.InvocationOnMock;
22 | import org.mockito.stubbing.Answer;
23 | import org.powermock.api.mockito.PowerMockito;
24 | import org.powermock.core.classloader.annotations.PowerMockIgnore;
25 | import org.powermock.core.classloader.annotations.PrepareForTest;
26 | import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
27 | import org.powermock.modules.junit4.rule.PowerMockRule;
28 | import org.robolectric.Robolectric;
29 | import org.robolectric.RobolectricTestRunner;
30 | import org.robolectric.android.controller.ActivityController;
31 | import org.robolectric.annotation.Config;
32 |
33 | import java.io.File;
34 |
35 | import static junit.framework.Assert.assertFalse;
36 | import static junit.framework.Assert.assertNotNull;
37 | import static junit.framework.Assert.assertTrue;
38 | import static org.powermock.api.mockito.PowerMockito.mock;
39 | import static org.powermock.api.mockito.PowerMockito.when;
40 |
41 | /**
42 | * Created by rusfearuth on 10.04.17.
43 | */
44 |
45 | @RunWith(RobolectricTestRunner.class)
46 | @SuppressStaticInitializationFor("com.facebook.react.common.build.ReactBuildConfig")
47 | @PrepareForTest({Arguments.class})
48 | @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
49 | @Config(manifest = Config.NONE)
50 | public class ImagePickerModuleTest
51 | {
52 | private static final int DEFAULT_THEME = R.style.DefaultExplainingPermissionsTheme;
53 |
54 | @Rule
55 | public PowerMockRule rule = new PowerMockRule();
56 |
57 | private ActivityController activityController;
58 | private Activity activity;
59 | private ReactApplicationContext reactContext;
60 |
61 | private TestableImagePickerModule module;
62 |
63 | @Before
64 | public void setUp() throws Exception
65 | {
66 | nativeMock();
67 |
68 | activityController = Robolectric.buildActivity(Activity.class);
69 | activity = activityController.create().start().resume().get();
70 | reactContext = mock(ReactApplicationContext.class);
71 |
72 | module = new TestableImagePickerModule(reactContext, DEFAULT_THEME);
73 | assertNotNull("Module was created", module);
74 | when(reactContext.getCurrentActivity()).thenReturn(activity);
75 | }
76 |
77 |
78 |
79 | @After
80 | public void tearDown()
81 | {
82 | activityController.pause().stop().destroy();
83 | activity = null;
84 | }
85 |
86 |
87 | @Test
88 | public void testCancelTakingPhoto()
89 | {
90 | final SampleCallback callback = new SampleCallback();
91 | module.setCallback(callback);
92 | module.setCameraCaptureUri(Uri.fromFile(new File("")));
93 | module.onActivityResult(activity, ImagePickerModule.REQUEST_LAUNCH_IMAGE_CAPTURE, Activity.RESULT_CANCELED, null);
94 | assertFalse("Camera's been launched", callback.hasError());
95 | assertTrue("User's cancelled of taking a photo", callback.didCancel());
96 | }
97 |
98 | private void nativeMock()
99 | {
100 | PowerMockito.mockStatic(Arguments.class);
101 | when(Arguments.createArray()).thenAnswer(new Answer