├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci-android-lint.yml │ ├── ci-build-debug.yml │ ├── ci-detekt.yml │ └── ci-ktlint.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── art ├── imagepicker_camera_demo.gif.gif ├── imagepicker_gallery_demo.gif.gif └── imagepicker_profile_demo.gif ├── build.gradle ├── detekt.yml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── imagepicker ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── github │ │ └── dhaval2404 │ │ └── imagepicker │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── kotlin │ │ └── com │ │ │ └── github │ │ │ └── dhaval2404 │ │ │ └── imagepicker │ │ │ ├── ImagePicker.kt │ │ │ ├── ImagePickerActivity.kt │ │ │ ├── ImagePickerFileProvider.kt │ │ │ ├── constant │ │ │ └── ImageProvider.kt │ │ │ ├── listener │ │ │ ├── DismissListener.kt │ │ │ └── ResultListener.kt │ │ │ ├── provider │ │ │ ├── BaseProvider.kt │ │ │ ├── CameraProvider.kt │ │ │ ├── CompressionProvider.kt │ │ │ ├── CropProvider.kt │ │ │ └── GalleryProvider.kt │ │ │ └── util │ │ │ ├── DialogHelper.kt │ │ │ ├── ExifDataCopier.kt │ │ │ ├── FileUriUtils.kt │ │ │ ├── FileUtil.kt │ │ │ ├── ImageUtil.kt │ │ │ ├── IntentUtils.kt │ │ │ └── PermissionUtil.kt │ └── res │ │ ├── drawable-hdpi │ │ ├── ic_photo_black_48dp.png │ │ └── ic_photo_camera_black_48dp.png │ │ ├── drawable-mdpi │ │ ├── ic_photo_black_48dp.png │ │ └── ic_photo_camera_black_48dp.png │ │ ├── drawable-xhdpi │ │ ├── ic_photo_black_48dp.png │ │ └── ic_photo_camera_black_48dp.png │ │ ├── drawable-xxhdpi │ │ ├── ic_photo_black_48dp.png │ │ └── ic_photo_camera_black_48dp.png │ │ ├── drawable-xxxhdpi │ │ ├── ic_photo_black_48dp.png │ │ └── ic_photo_camera_black_48dp.png │ │ ├── layout │ │ └── dialog_choose_app.xml │ │ ├── values-ar │ │ └── strings.xml │ │ ├── values-de │ │ └── strings.xml │ │ ├── values-es │ │ └── strings.xml │ │ ├── values-fa │ │ └── strings.xml │ │ ├── values-fr │ │ └── strings.xml │ │ ├── values-gu │ │ └── strings.xml │ │ ├── values-hi │ │ └── strings.xml │ │ ├── values-in │ │ └── strings.xml │ │ ├── values-nb-rNO │ │ └── strings.xml │ │ ├── values-pl │ │ └── strings.xml │ │ ├── values-pt-rBR │ │ └── strings.xml │ │ ├── values-tr │ │ └── strings.xml │ │ ├── values-uz │ │ └── strings.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ │ └── xml │ │ └── image_picker_provider_paths.xml │ └── test │ └── java │ └── com │ └── github │ └── dhaval2404 │ └── imagepicker │ └── ExampleUnitTest.kt ├── ktlint.gradle ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── github │ │ └── dhaval2404 │ │ └── imagepicker │ │ ├── ExampleInstrumentedTest.kt │ │ └── MainActivityEspressoTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── ic_launcher-web.png │ ├── kotlin │ │ └── com.github.dhaval2404.imagepicker │ │ │ └── sample │ │ │ ├── ImageViewExtension.kt │ │ │ ├── ImageViewerDialog.kt │ │ │ ├── MainActivity.kt │ │ │ ├── SampleActivity.java │ │ │ └── util │ │ │ ├── FileUtil.kt │ │ │ └── IntentUtil.kt │ └── res │ │ ├── drawable-hdpi │ │ └── ic_github.png │ │ ├── drawable │ │ ├── baseline_photo_24.xml │ │ ├── baseline_photo_camera_24.xml │ │ ├── ic_person.xml │ │ ├── img_camera_code.png │ │ ├── img_gallery_code.png │ │ ├── img_profile_code.png │ │ ├── outline_cloud_upload_24.xml │ │ ├── outline_code_24.xml │ │ ├── outline_info_24.xml │ │ └── profile_bg.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── content_camera_only.xml │ │ ├── content_gallery_only.xml │ │ ├── content_main.xml │ │ ├── content_profile.xml │ │ └── dialog_imageviewer.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── ic_launcher_background.xml │ │ ├── material_colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── github │ └── dhaval2404 │ └── imagepicker │ └── ExampleUnitTest.kt └── settings.gradle /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 15 | 16 | ## Summary 17 | 18 | 19 | ## Code to reproduce 20 | 21 | 22 | ## Android version 23 | 24 | 25 | ## Impacted devices 26 | 27 | 28 | ## Installation method 29 | 30 | 31 | ## SDK version 32 | 35 | 36 | ## Other information 37 | 38 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 🚀 Description 4 | 5 | 6 | ## 📄 Motivation and Context 7 | 8 | 9 | 10 | ## 🧪 How Has This Been Tested? 11 | 12 | 13 | 14 | 15 | ## 📷 Screenshots (if appropriate) 16 | 17 | 18 | ## 📦 Types of changes 19 | 20 | - [ ] Bug fix (non-breaking change which fixes an issue) 21 | - [ ] New feature (non-breaking change which adds functionality) 22 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 23 | 24 | ## ✅ Checklist 25 | 26 | 27 | - [ ] My code follows the code style of this project. 28 | - [ ] My change requires a change to the documentation. 29 | - [ ] I have updated the documentation accordingly. 30 | -------------------------------------------------------------------------------- /.github/workflows/ci-android-lint.yml: -------------------------------------------------------------------------------- 1 | name: android lint 2 | 3 | on: 4 | push: 5 | branches: [master] # Just in case master was not up to date while merging PR 6 | pull_request: 7 | types: [opened, synchronize] 8 | 9 | jobs: 10 | run: 11 | continue-on-error: true 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | steps: 16 | - name: Checkout Repo 17 | uses: actions/checkout@v2 18 | 19 | - name: Set up JDK 1.8 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.8 23 | 24 | - name: Make Gradle executable 25 | run: chmod +x ./gradlew 26 | 27 | - uses: finnp/create-file-action@master 28 | env: 29 | FILE_NAME: "local.properties" 30 | 31 | - name: lint 32 | run: ./gradlew lint 33 | 34 | - uses: actions/upload-artifact@v2 35 | with: 36 | name: android-lint-report 37 | path: ~/app/build/reports/lint-results.html 38 | 39 | - uses: actions/upload-artifact@v2 40 | with: 41 | name: android-lint-report 42 | path: ./**/build/reports/lint-results.xml -------------------------------------------------------------------------------- /.github/workflows/ci-build-debug.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | types: [opened, synchronize] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout Repo 14 | uses: actions/checkout@v2 15 | 16 | - name: set up JDK 1.8 17 | uses: actions/setup-java@v1 18 | with: 19 | java-version: 1.8 20 | 21 | - name: Make Gradle executable 22 | run: chmod +x ./gradlew 23 | 24 | - uses: finnp/create-file-action@master 25 | env: 26 | FILE_NAME: "local.properties" 27 | 28 | - name: Build with Gradle 29 | run: ./gradlew build 30 | 31 | - name: Build Debug APK 32 | run: ./gradlew assembleDebug -------------------------------------------------------------------------------- /.github/workflows/ci-detekt.yml: -------------------------------------------------------------------------------- 1 | name: detekt 2 | 3 | on: 4 | push: 5 | branches: [master] # Just in case master was not up to date while merging PR 6 | pull_request: 7 | types: [opened, synchronize] 8 | 9 | jobs: 10 | run: 11 | continue-on-error: true 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | steps: 16 | - name: Checkout Repo 17 | uses: actions/checkout@v2 18 | 19 | - name: Set up JDK 1.8 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.8 23 | 24 | - name: Make Gradle executable 25 | run: chmod +x ./gradlew 26 | 27 | - uses: finnp/create-file-action@master 28 | env: 29 | FILE_NAME: "local.properties" 30 | 31 | - name: detekt 32 | run: ./gradlew detekt 33 | 34 | - uses: actions/upload-artifact@v2 35 | with: 36 | name: detekt-report 37 | path: ./**/build/reports/detekt/detekt.* -------------------------------------------------------------------------------- /.github/workflows/ci-ktlint.yml: -------------------------------------------------------------------------------- 1 | name: ktlint 2 | 3 | on: 4 | push: 5 | branches: [master] # Just in case master was not up to date while merging PR 6 | pull_request: 7 | types: [opened, synchronize] 8 | 9 | jobs: 10 | run: 11 | continue-on-error: true 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | steps: 16 | - name: Checkout Repo 17 | uses: actions/checkout@v2 18 | 19 | - name: Set up JDK 1.8 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.8 23 | 24 | - name: Make Gradle executable 25 | run: chmod +x ./gradlew 26 | 27 | - uses: finnp/create-file-action@master 28 | env: 29 | FILE_NAME: "local.properties" 30 | 31 | - name: ktlint 32 | run: ./gradlew ktlint 33 | 34 | - uses: actions/upload-artifact@v2 35 | with: 36 | name: ktlint-report 37 | path: ./**/build/reports/ktlint/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | /.idea/vcs.xml 11 | /.idea/misc.xml 12 | /.idea/gradle.xml 13 | /.idea/runConfigurations.xml 14 | /.idea/codeStyles 15 | /.idea/dictionaries 16 | /.idea/icon.png 17 | /.idea/jarRepositories.xml 18 | /.idea/compiler.xml 19 | .DS_Store 20 | /build 21 | /captures 22 | .externalNativeBuild 23 | .idea/encodings.xml 24 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # ✔️Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [2.1] - 2021-05-27 10 | ### Added 11 | * Added uzbekistan translation (Special Thanks to Khudoyshukur Juraev) 12 | ### Changed 13 | * Removed requestLegacyExternalStorage flag 14 | * Removed unused string resources 15 | 16 | ## [2.0] - 2021-05-15 17 | ### Added 18 | * Added arabic translation [#157](https://github.com/Dhaval2404/ImagePicker/pull/157) (Special Thanks to [zhangzhu95](https://github.com/zhangzhu95)) 19 | * Added norwegian translation [#163](https://github.com/Dhaval2404/ImagePicker/pull/163) (Special Thanks to [TorkelV](https://github.com/TorkelV)) 20 | * Added german translation [#192](https://github.com/Dhaval2404/ImagePicker/pull/192) (Special Thanks to [MDXDave](https://github.com/MDXDave)) 21 | * Added method to return Intent for manual launching ImagePicker [#182](https://github.com/Dhaval2404/ImagePicker/pull/182) (Special Thanks to [tobiasKaminsky](https://github.com/tobiasKaminsky)) 22 | * Added support for android 11 [#199](https://github.com/Dhaval2404/ImagePicker/issues/199) 23 | ### Changed 24 | * Fixed Playstore requestLegacyExternalStorage flag issue [#199](https://github.com/Dhaval2404/ImagePicker/issues/199) 25 | * Fixed android scope storage issue [#29](https://github.com/Dhaval2404/ImagePicker/issues/29) 26 | * Removed storage permissions [#29](https://github.com/Dhaval2404/ImagePicker/issues/29) 27 | * Fixed calculateInSampleSize leads to overly degraded quality [#152](https://github.com/Dhaval2404/ImagePicker/issues/152) (Special Thanks to [FlorianDenis](https://github.com/FlorianDenis)) 28 | * Fixed camera app not found issue [#162](https://github.com/Dhaval2404/ImagePicker/issues/162) 29 | 30 | ## [1.8] - 2020-12-22 31 | ### Added 32 | * Added dialog dismiss listener (Special Thanks to [kibotu](https://github.com/kibotu)) 33 | * Added text localization (Special Thanks to [yamin8000](https://github.com/yamin8000) and Jose Bravo) 34 | ### Changed 35 | * Fixed crash issue on missing camera app [#69](https://github.com/Dhaval2404/ImagePicker/issues/69) 36 | * Fixed issue selecting images from download folder [#86](https://github.com/Dhaval2404/ImagePicker/issues/86) 37 | * Fixed exif information lost issue [#121](https://github.com/Dhaval2404/ImagePicker/issues/121) 38 | * Fixed crash issue on large image crop [#122](https://github.com/Dhaval2404/ImagePicker/issues/122) 39 | * Fixed saving image in cache issue [#127](https://github.com/Dhaval2404/ImagePicker/issues/127) 40 | 41 | ## [1.7.5] - 2020-08-30 42 | ### Changed 43 | * Added Polish text translation [#115](https://github.com/Dhaval2404/ImagePicker/issues/115) (Special Thanks to [MarcelKijanka](https://github.com/MarcelKijanka)) 44 | * Failed to find configured root exception [#116](https://github.com/Dhaval2404/ImagePicker/issues/116) 45 | 46 | ## [1.7.4] - 2020-08-02 47 | ### Changed 48 | * Fixed PNG image saved as JPG after compress issue [#105](https://github.com/Dhaval2404/ImagePicker/issues/105) 49 | 50 | ## [1.7.3] - 2020-07-18 51 | ### Changed 52 | * Fixed PNG image saved as JPG after crop issue [#94](https://github.com/Dhaval2404/ImagePicker/issues/94) 53 | 54 | ## [1.7.2] - 2020-07-14 55 | ### Changed 56 | * Fixed .crop() opening gallery or camera twice [#32](https://github.com/Dhaval2404/ImagePicker/issues/32) 57 | * Fixed UCropActivity Crash Android 4.4 (KiKat) [#82](https://github.com/Dhaval2404/ImagePicker/issues/82) 58 | 59 | ## [1.7.1] - 2020-03-26 60 | ### Changed 61 | * Fixed The application could not be installed: INSTALL_FAILED_CONFLICTING_PROVIDER issue [#67](https://github.com/Dhaval2404/ImagePicker/issues/67) 62 | 63 | ## [1.7] - 2020-03-23 64 | ### Changed 65 | * Added option to limit MIME types while choosing a gallery image (Special Thanks to [Marchuck](https://github.com/Marchuck)) 66 | * Introduced ImageProviderInterceptor, Can be used for analytics (Special Thanks to [Marchuck](https://github.com/Marchuck)) 67 | * Fixed FileProvider of the library clashes with the FileProvider of the app [#51](https://github.com/Dhaval2404/ImagePicker/issues/51) (Special Thanks to [OyaCanli](https://github.com/OyaCanli)) 68 | * Added option to set Storage Directory [#52](https://github.com/Dhaval2404/ImagePicker/issues/52) 69 | * Fixed NullPointerException in FileUriUtils.getPathFromRemoteUri() [#61](https://github.com/Dhaval2404/ImagePicker/issues/61) (Special Thanks to [himphen](https://github.com/himphen)) 70 | 71 | ## [1.6] - 2020-01-06 72 | ### Changed 73 | * Improved UI/UX of sample app 74 | * Removed Bitmap Deprecated Property [#33](https://github.com/Dhaval2404/ImagePicker/issues/33) (Special Thanks to [nauhalf](https://github.com/nauhalf)) 75 | * Camera opens twice when "Don't keep activities" option is ON [#41](https://github.com/Dhaval2404/ImagePicker/issues/41) (Special Thanks to [benji101](https://github.com/benji101)) 76 | * Fixed uCrop Crash Issue [#42](https://github.com/Dhaval2404/ImagePicker/issues/42) 77 | 78 | ## [1.5] - 2019-10-14 79 | ### Added 80 | * Added Option for Dynamic Crop Ratio. Let User choose aspect ratio [#36](https://github.com/Dhaval2404/ImagePicker/issues/36) (Special Thanks to [Dor-Sloim](https://github.com/Dor-Sloim)) 81 | ### Changed 82 | * Fixed app crash issue, due to Camera Permission in manifest [#34](https://github.com/Dhaval2404/ImagePicker/issues/34) 83 | 84 | ## [1.4] - 2019-09-03 85 | ### Changed 86 | * Optimized Uri to File Conversion (Inspired by [Flutter ImagePicker](https://github.com/flutter/plugins/tree/master/packages/image_picker)) 87 | ### Removed 88 | * Removed redundant CAMERA permission [#26](https://github.com/Dhaval2404/ImagePicker/issues/26) (Special Thanks to [PerrchicK](https://github.com/PerrchicK)) 89 | 90 | ## [1.3] - 2019-07-24 91 | ### Added 92 | * Sample app made compatible with Android Kitkat 4.4+ (API 19) 93 | ### Changed 94 | * Fixed Uri to File Conversion issue [#8](https://github.com/Dhaval2404/ImagePicker/issues/8) (Special Thanks to [squeeish](https://github.com/squeeish)) 95 | 96 | ## [1.2] - 2019-05-13 97 | ### Added 98 | * Added Support for Inline Activity Result(Special Thanks to [soareseneves](https://github.com/soareseneves)) 99 | ### Changed 100 | * Fixed issue [#6](https://github.com/Dhaval2404/ImagePicker/issues/6) 101 | 102 | ## [1.1] - 2019-04-02 103 | ### Changed 104 | * Optimized Compression Logic 105 | * Replace white screen with transparent one. 106 | 107 | ## [1.0] - 2019-02-11 108 | ### Added 109 | * Pick Gallery Image 110 | * Capture Camera Image 111 | * Crop Image(Its based on [uCrop](https://github.com/Yalantis/uCrop)) 112 | * Compress Image(Compress image based on resolution and size) 113 | * Handle Runtime Permission for Camera and Storage 114 | * Retrieve Image Result as File, File Path as String or Uri object 115 | 116 | [Unreleased]: https://github.com/Dhaval2404/ImagePicker/compare/v2.2...HEAD 117 | [2.1]: https://github.com/Dhaval2404/ImagePicker/compare/v2.0...v2.1 118 | [2.0]: https://github.com/Dhaval2404/ImagePicker/compare/v1.8...v2.0 119 | [1.8]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7.5...v1.8 120 | [1.7.5]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7.4...v1.7.5 121 | [1.7.4]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7.3...v1.7.4 122 | [1.7.3]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7.2...v1.7.3 123 | [1.7.2]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7.1...v1.7.2 124 | [1.7.1]: https://github.com/Dhaval2404/ImagePicker/compare/v1.7...v1.7.1 125 | [1.7]: https://github.com/Dhaval2404/ImagePicker/compare/v1.6...v1.7 126 | [1.6]: https://github.com/Dhaval2404/ImagePicker/compare/v1.5...v1.6 127 | [1.5]: https://github.com/Dhaval2404/ImagePicker/compare/v1.4...v1.5 128 | [1.4]: https://github.com/Dhaval2404/ImagePicker/compare/v1.3...v1.4 129 | [1.3]: https://github.com/Dhaval2404/ImagePicker/compare/v1.2...v1.3 130 | [1.2]: https://github.com/Dhaval2404/ImagePicker/compare/v1.1...v1.2 131 | [1.1]: https://github.com/Dhaval2404/ImagePicker/compare/v1.0...v1.1 132 | [1.0]: https://github.com/Dhaval2404/ImagePicker/tree/v1.0 133 | 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019-2021, Dhaval Patel 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /art/imagepicker_camera_demo.gif.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/art/imagepicker_camera_demo.gif.gif -------------------------------------------------------------------------------- /art/imagepicker_gallery_demo.gif.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/art/imagepicker_gallery_demo.gif.gif -------------------------------------------------------------------------------- /art/imagepicker_profile_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/art/imagepicker_profile_demo.gif -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.4.0' 5 | repositories { 6 | google() 7 | maven { url "https://jitpack.io" } 8 | jcenter() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:4.2.0' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.15.0" 14 | } 15 | } 16 | 17 | allprojects { 18 | apply plugin: "io.gitlab.arturbosch.detekt" 19 | 20 | repositories { 21 | google() 22 | maven { url "https://jitpack.io" } 23 | jcenter() 24 | } 25 | 26 | detekt { 27 | config = files("${project.rootDir}/detekt.yml") 28 | parallel = true 29 | } 30 | 31 | // Avoid Kotlin docs error 32 | tasks.withType(Javadoc) { 33 | enabled = false 34 | } 35 | 36 | } 37 | 38 | task clean(type: Delete) { 39 | delete rootProject.buildDir 40 | } 41 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jun 07 23:33:12 IST 2019 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-6.9-all.zip -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 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 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /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 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 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 Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /imagepicker/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /imagepicker/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'kotlin-android' 4 | } 5 | 6 | apply from: "../ktlint.gradle" 7 | 8 | android { 9 | compileSdkVersion 30 10 | 11 | defaultConfig { 12 | minSdkVersion 19 13 | targetSdkVersion 30 14 | versionCode 16 15 | versionName "2.1" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | debug{ 22 | 23 | } 24 | release { 25 | minifyEnabled false 26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 27 | } 28 | } 29 | 30 | sourceSets { 31 | main.java.srcDirs += 'src/main/kotlin' 32 | } 33 | 34 | compileOptions { 35 | sourceCompatibility JavaVersion.VERSION_1_8 36 | targetCompatibility JavaVersion.VERSION_1_8 37 | } 38 | 39 | } 40 | 41 | dependencies { 42 | implementation fileTree(dir: 'libs', include: ['*.jar']) 43 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 44 | 45 | implementation 'androidx.core:core-ktx:1.3.2' 46 | implementation 'androidx.appcompat:appcompat:1.2.0' 47 | 48 | implementation "androidx.exifinterface:exifinterface:1.3.2" 49 | implementation 'androidx.documentfile:documentfile:1.0.1' 50 | 51 | //More Info: https://github.com/Yalantis/uCrop 52 | implementation 'com.github.yalantis:ucrop:2.2.6' 53 | 54 | testImplementation 'junit:junit:4.13.2' 55 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 56 | androidTestImplementation 'androidx.test:core:1.3.0' 57 | } 58 | 59 | ext { 60 | bintrayRepo = 'maven' 61 | bintrayName = 'imagepicker' 62 | 63 | publishedGroupId = 'com.github.dhaval2404' 64 | libraryName = 'imagepicker' 65 | artifact = 'imagepicker' 66 | 67 | libraryDescription = 'Pick image from Gallery or Capture new image with Camera.' 68 | 69 | siteUrl = 'https://github.com/Dhaval2404/ImagePicker/' 70 | gitUrl = 'https://github.com/Dhaval2404/ImagePicker.git' 71 | 72 | libraryVersion = '2.1' 73 | //If you are uploading new library try : gradlew install 74 | //If you are updating existing library then execute: gradlew bintrayUpload 75 | //In both the case don't forgot to put bintray credentials in local.properties file. 76 | 77 | developerId = 'dhaval2404' 78 | developerName = 'Dhaval Patel' 79 | developerEmail = 'dhavalpatel244@gmail.com' 80 | 81 | licenseName = 'The Apache Software License, Version 2.0' 82 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 83 | allLicenses = ["Apache-2.0"] 84 | } 85 | -------------------------------------------------------------------------------- /imagepicker/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /imagepicker/src/androidTest/java/com/github/dhaval2404/imagepicker/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import androidx.test.InstrumentationRegistry 4 | import org.junit.Assert.assertEquals 5 | import org.junit.Test 6 | 7 | /** 8 | * Instrumented test, which will execute on an Android device. 9 | * 10 | * @see Testing documentation 11 | */ 12 | class ExampleInstrumentedTest { 13 | @Test 14 | fun useAppContext() { 15 | // Context of the app under test. 16 | val appContext = InstrumentationRegistry.getTargetContext() 17 | 18 | assertEquals("com.github.dhaval2404.imagepicker.test", appContext.packageName) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /imagepicker/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 21 | 22 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/ImagePickerActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import android.app.Activity 4 | import android.content.Context 5 | import android.content.Intent 6 | import android.net.Uri 7 | import android.os.Bundle 8 | import android.util.Log 9 | import androidx.appcompat.app.AppCompatActivity 10 | import com.github.dhaval2404.imagepicker.constant.ImageProvider 11 | import com.github.dhaval2404.imagepicker.provider.CameraProvider 12 | import com.github.dhaval2404.imagepicker.provider.CompressionProvider 13 | import com.github.dhaval2404.imagepicker.provider.CropProvider 14 | import com.github.dhaval2404.imagepicker.provider.GalleryProvider 15 | import com.github.dhaval2404.imagepicker.util.FileUriUtils 16 | 17 | /** 18 | * Pick Image 19 | * 20 | * @author Dhaval Patel 21 | * @version 1.0 22 | * @since 04 January 2019 23 | */ 24 | class ImagePickerActivity : AppCompatActivity() { 25 | 26 | companion object { 27 | private const val TAG = "image_picker" 28 | 29 | internal fun getCancelledIntent(context: Context): Intent { 30 | val intent = Intent() 31 | val message = context.getString(R.string.error_task_cancelled) 32 | intent.putExtra(ImagePicker.EXTRA_ERROR, message) 33 | return intent 34 | } 35 | } 36 | 37 | private var mGalleryProvider: GalleryProvider? = null 38 | private var mCameraProvider: CameraProvider? = null 39 | private lateinit var mCropProvider: CropProvider 40 | private lateinit var mCompressionProvider: CompressionProvider 41 | 42 | override fun onCreate(savedInstanceState: Bundle?) { 43 | super.onCreate(savedInstanceState) 44 | loadBundle(savedInstanceState) 45 | } 46 | 47 | /** 48 | * Save all appropriate activity state. 49 | */ 50 | public override fun onSaveInstanceState(outState: Bundle) { 51 | mCameraProvider?.onSaveInstanceState(outState) 52 | mCropProvider.onSaveInstanceState(outState) 53 | super.onSaveInstanceState(outState) 54 | } 55 | 56 | /** 57 | * Parse Intent Bundle and initialize variables 58 | */ 59 | private fun loadBundle(savedInstanceState: Bundle?) { 60 | // Create Crop Provider 61 | mCropProvider = CropProvider(this) 62 | mCropProvider.onRestoreInstanceState(savedInstanceState) 63 | 64 | // Create Compression Provider 65 | mCompressionProvider = CompressionProvider(this) 66 | 67 | // Retrieve Image Provider 68 | val provider: ImageProvider? = 69 | intent?.getSerializableExtra(ImagePicker.EXTRA_IMAGE_PROVIDER) as ImageProvider? 70 | 71 | // Create Gallery/Camera Provider 72 | when (provider) { 73 | ImageProvider.GALLERY -> { 74 | mGalleryProvider = GalleryProvider(this) 75 | // Pick Gallery Image 76 | savedInstanceState ?: mGalleryProvider?.startIntent() 77 | } 78 | ImageProvider.CAMERA -> { 79 | mCameraProvider = CameraProvider(this) 80 | mCameraProvider?.onRestoreInstanceState(savedInstanceState) 81 | // Pick Camera Image 82 | savedInstanceState ?: mCameraProvider?.startIntent() 83 | } 84 | else -> { 85 | // Something went Wrong! This case should never happen 86 | Log.e(TAG, "Image provider can not be null") 87 | setError(getString(R.string.error_task_cancelled)) 88 | } 89 | } 90 | } 91 | 92 | /** 93 | * Dispatch incoming result to the correct provider. 94 | */ 95 | override fun onRequestPermissionsResult( 96 | requestCode: Int, 97 | permissions: Array, 98 | grantResults: IntArray 99 | ) { 100 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 101 | mCameraProvider?.onRequestPermissionsResult(requestCode) 102 | } 103 | 104 | /** 105 | * Dispatch incoming result to the correct provider. 106 | */ 107 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 108 | super.onActivityResult(requestCode, resultCode, data) 109 | mCameraProvider?.onActivityResult(requestCode, resultCode, data) 110 | mGalleryProvider?.onActivityResult(requestCode, resultCode, data) 111 | mCropProvider.onActivityResult(requestCode, resultCode, data) 112 | } 113 | 114 | /** 115 | * Handle Activity Back Press 116 | */ 117 | override fun onBackPressed() { 118 | setResultCancel() 119 | } 120 | 121 | /** 122 | * {@link CameraProvider} and {@link GalleryProvider} Result will be available here. 123 | * 124 | * @param uri Capture/Gallery image Uri 125 | */ 126 | fun setImage(uri: Uri) { 127 | when { 128 | mCropProvider.isCropEnabled() -> mCropProvider.startIntent(uri) 129 | mCompressionProvider.isCompressionRequired(uri) -> mCompressionProvider.compress(uri) 130 | else -> setResult(uri) 131 | } 132 | } 133 | 134 | /** 135 | * {@link CropProviders} Result will be available here. 136 | * 137 | * Check if compression is enable/required. If yes then start compression else return result. 138 | * 139 | * @param uri Crop image uri 140 | */ 141 | fun setCropImage(uri: Uri) { 142 | // Delete Camera file after crop. Else there will be two image for the same action. 143 | // In case of Gallery Provider, we will get original image path, so we will not delete that. 144 | mCameraProvider?.delete() 145 | 146 | if (mCompressionProvider.isCompressionRequired(uri)) { 147 | mCompressionProvider.compress(uri) 148 | } else { 149 | setResult(uri) 150 | } 151 | } 152 | 153 | /** 154 | * {@link CompressionProvider} Result will be available here. 155 | * 156 | * @param uri Compressed image Uri 157 | */ 158 | fun setCompressedImage(uri: Uri) { 159 | // This is the case when Crop is not enabled 160 | 161 | // Delete Camera file after crop. Else there will be two image for the same action. 162 | // In case of Gallery Provider, we will get original image path, so we will not delete that. 163 | mCameraProvider?.delete() 164 | 165 | // If crop file is not null, Delete it after crop 166 | mCropProvider.delete() 167 | 168 | setResult(uri) 169 | } 170 | 171 | /** 172 | * Set Result, Image is successfully capture/picked/cropped/compressed. 173 | * 174 | * @param uri final image Uri 175 | */ 176 | private fun setResult(uri: Uri) { 177 | val intent = Intent() 178 | intent.data = uri 179 | intent.putExtra(ImagePicker.EXTRA_FILE_PATH, FileUriUtils.getRealPath(this, uri)) 180 | setResult(Activity.RESULT_OK, intent) 181 | finish() 182 | } 183 | 184 | /** 185 | * User has cancelled the task 186 | */ 187 | fun setResultCancel() { 188 | setResult(Activity.RESULT_CANCELED, getCancelledIntent(this)) 189 | finish() 190 | } 191 | 192 | /** 193 | * Error occurred while processing image 194 | * 195 | * @param message Error Message 196 | */ 197 | fun setError(message: String) { 198 | val intent = Intent() 199 | intent.putExtra(ImagePicker.EXTRA_ERROR, message) 200 | setResult(ImagePicker.RESULT_ERROR, intent) 201 | finish() 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/ImagePickerFileProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import androidx.core.content.FileProvider 4 | 5 | class ImagePickerFileProvider : FileProvider() 6 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/constant/ImageProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.constant 2 | 3 | /** 4 | * Define Image Provider 5 | * 6 | * @author Dhaval Patel 7 | * @version 1.0 8 | * @since 04 January 2019 9 | */ 10 | enum class ImageProvider { 11 | GALLERY, 12 | CAMERA, 13 | BOTH 14 | } 15 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/listener/DismissListener.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.listener 2 | 3 | /** 4 | * Interface used to allow the creator of a dialog to run some code when the 5 | * dialog is dismissed. 6 | * 7 | * @author Dhaval Patel 8 | * @version 1.8 9 | * @since 19 December 2020 10 | */ 11 | interface DismissListener { 12 | 13 | /** 14 | * This method will be invoked when the dialog is dismissed. 15 | */ 16 | fun onDismiss() 17 | } 18 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/listener/ResultListener.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.listener 2 | 3 | /** 4 | * 5 | * Generic Class To Listen Async Result 6 | * 7 | * @author Dhaval Patel 8 | * @version 1.0 9 | * @since 04 January 2018 10 | */ 11 | internal interface ResultListener { 12 | 13 | fun onResult(t: T?) 14 | } 15 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/provider/BaseProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.provider 2 | 3 | import android.content.ContextWrapper 4 | import android.os.Bundle 5 | import android.os.Environment 6 | import com.github.dhaval2404.imagepicker.ImagePickerActivity 7 | import java.io.File 8 | 9 | /** 10 | * Abstract Provider class 11 | * 12 | * @author Dhaval Patel 13 | * @version 1.0 14 | * @since 04 January 2019 15 | */ 16 | abstract class BaseProvider(protected val activity: ImagePickerActivity) : 17 | ContextWrapper(activity) { 18 | 19 | fun getFileDir(path: String?): File { 20 | return if (path != null) File(path) 21 | else getExternalFilesDir(Environment.DIRECTORY_DCIM) ?: activity.filesDir 22 | } 23 | 24 | /** 25 | * Cancel operation and Set Error Message 26 | * 27 | * @param error Error Message 28 | */ 29 | protected fun setError(error: String) { 30 | onFailure() 31 | activity.setError(error) 32 | } 33 | 34 | /** 35 | * Cancel operation and Set Error Message 36 | * 37 | * @param errorRes Error Message 38 | */ 39 | protected fun setError(errorRes: Int) { 40 | setError(getString(errorRes)) 41 | } 42 | 43 | /** 44 | * Call this method when task is cancel in between the operation. 45 | * E.g. user hit back-press 46 | */ 47 | protected fun setResultCancel() { 48 | onFailure() 49 | activity.setResultCancel() 50 | } 51 | 52 | /** 53 | * This method will be Call on Error, It can be used for clean up Tasks 54 | */ 55 | protected open fun onFailure() { 56 | } 57 | 58 | /** 59 | * Save all appropriate provider state. 60 | */ 61 | open fun onSaveInstanceState(outState: Bundle) { 62 | } 63 | 64 | /** 65 | * Restores the saved state for all Providers. 66 | * 67 | * @param savedInstanceState the Bundle returned by {@link #onSaveInstanceState()} 68 | * @see #onSaveInstanceState() 69 | */ 70 | open fun onRestoreInstanceState(savedInstanceState: Bundle?) { 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/provider/CameraProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.provider 2 | 3 | import android.Manifest 4 | import android.app.Activity 5 | import android.content.Context 6 | import android.content.Intent 7 | import android.net.Uri 8 | import android.os.Bundle 9 | import androidx.core.app.ActivityCompat.requestPermissions 10 | import com.github.dhaval2404.imagepicker.ImagePicker 11 | import com.github.dhaval2404.imagepicker.ImagePickerActivity 12 | import com.github.dhaval2404.imagepicker.R 13 | import com.github.dhaval2404.imagepicker.util.FileUtil 14 | import com.github.dhaval2404.imagepicker.util.IntentUtils 15 | import com.github.dhaval2404.imagepicker.util.PermissionUtil 16 | import java.io.File 17 | 18 | /** 19 | * Capture new image using camera 20 | * 21 | * @author Dhaval Patel 22 | * @version 1.0 23 | * @since 04 January 2019 24 | */ 25 | class CameraProvider(activity: ImagePickerActivity) : BaseProvider(activity) { 26 | 27 | companion object { 28 | /** 29 | * Key to Save/Retrieve Camera File state 30 | */ 31 | private const val STATE_CAMERA_FILE = "state.camera_file" 32 | 33 | /** 34 | * Permission Require for Image Capture using Camera 35 | */ 36 | private val REQUIRED_PERMISSIONS = arrayOf( 37 | Manifest.permission.CAMERA 38 | ) 39 | 40 | private const val CAMERA_INTENT_REQ_CODE = 4281 41 | private const val PERMISSION_INTENT_REQ_CODE = 4282 42 | } 43 | 44 | /** 45 | * Temp Camera File 46 | */ 47 | private var mCameraFile: File? = null 48 | 49 | /** 50 | * Camera image will be stored in below file directory 51 | */ 52 | private val mFileDir: File 53 | 54 | init { 55 | val bundle = activity.intent.extras ?: Bundle() 56 | 57 | // Get File Directory 58 | val fileDir = bundle.getString(ImagePicker.EXTRA_SAVE_DIRECTORY) 59 | mFileDir = getFileDir(fileDir) 60 | } 61 | 62 | /** 63 | * Save CameraProvider state 64 | 65 | * mCameraFile will lose its state when activity is recreated on 66 | * Orientation change or for Low memory device. 67 | * 68 | * Here, We Will save its state for later use 69 | * 70 | * Note: To produce this scenario, enable "Don't keep activities" from developer options 71 | **/ 72 | override fun onSaveInstanceState(outState: Bundle) { 73 | // Save Camera File 74 | outState.putSerializable(STATE_CAMERA_FILE, mCameraFile) 75 | } 76 | 77 | /** 78 | * Retrieve CameraProvider state 79 | */ 80 | override fun onRestoreInstanceState(savedInstanceState: Bundle?) { 81 | // Restore Camera File 82 | mCameraFile = savedInstanceState?.getSerializable(STATE_CAMERA_FILE) as File? 83 | } 84 | 85 | /** 86 | * Start Camera Intent 87 | * 88 | * Create Temporary File object and Pass it to Camera Intent 89 | */ 90 | fun startIntent() { 91 | if (!IntentUtils.isCameraAppAvailable(this)) { 92 | setError(R.string.error_camera_app_not_found) 93 | return 94 | } 95 | 96 | checkPermission() 97 | } 98 | 99 | /** 100 | * Check Require permission for Taking Picture. 101 | * 102 | * If permission is not granted request Permission, Else start Camera Intent 103 | */ 104 | private fun checkPermission() { 105 | if (isPermissionGranted(this)) { 106 | // Permission Granted, Start Camera Intent 107 | startCameraIntent() 108 | } else { 109 | // Request Permission 110 | requestPermission() 111 | } 112 | } 113 | 114 | /** 115 | * Start Camera Intent 116 | * 117 | * Create Temporary File object and Pass it to Camera Intent 118 | */ 119 | private fun startCameraIntent() { 120 | // Create and get empty file to store capture image content 121 | val file = FileUtil.getImageFile(fileDir = mFileDir) 122 | mCameraFile = file 123 | 124 | // Check if file exists 125 | if (file != null && file.exists()) { 126 | val cameraIntent = IntentUtils.getCameraIntent(this, file) 127 | activity.startActivityForResult(cameraIntent, CAMERA_INTENT_REQ_CODE) 128 | } else { 129 | setError(R.string.error_failed_to_create_camera_image_file) 130 | } 131 | } 132 | 133 | /** 134 | * Request Runtime Permission required for Taking Pictures. 135 | * Ref: https://github.com/Dhaval2404/ImagePicker/issues/34 136 | */ 137 | private fun requestPermission() { 138 | requestPermissions(activity, getRequiredPermission(activity), PERMISSION_INTENT_REQ_CODE) 139 | } 140 | 141 | /** 142 | * Check if require permission granted for Taking Picture. 143 | * Ref: https://github.com/Dhaval2404/ImagePicker/issues/34 144 | * 145 | * @param context Application Context 146 | * @return boolean true if all required permission granted else false. 147 | */ 148 | private fun isPermissionGranted(context: Context): Boolean { 149 | return getRequiredPermission(context).none { 150 | !PermissionUtil.isPermissionGranted(context, it) 151 | } 152 | } 153 | 154 | /** 155 | * Check if permission Exists in Manifest 156 | * 157 | * @param context Application Context 158 | * @return Array returns permission which are added in Manifest 159 | */ 160 | private fun getRequiredPermission(context: Context): Array { 161 | return REQUIRED_PERMISSIONS.filter { 162 | PermissionUtil.isPermissionInManifest(context, it) 163 | }.toTypedArray() 164 | } 165 | 166 | /** 167 | * Handle Requested Permission Result 168 | */ 169 | fun onRequestPermissionsResult(requestCode: Int) { 170 | if (requestCode == PERMISSION_INTENT_REQ_CODE) { 171 | // Check again if permission is granted 172 | if (isPermissionGranted(this)) { 173 | // Permission is granted, Start Camera Intent 174 | startIntent() 175 | } else { 176 | // Exit with error message 177 | val error = getString(R.string.permission_camera_denied) 178 | setError(error) 179 | } 180 | } 181 | } 182 | 183 | /** 184 | * Handle Camera Intent Activity Result 185 | * 186 | * @param requestCode It must be {@link CameraProvider#CAMERA_INTENT_REQ_CODE} 187 | * @param resultCode For success it should be {@link Activity#RESULT_OK} 188 | * @param data Result Intent 189 | */ 190 | @Suppress("UNUSED_PARAMETER") 191 | fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 192 | if (requestCode == CAMERA_INTENT_REQ_CODE) { 193 | if (resultCode == Activity.RESULT_OK) { 194 | handleResult() 195 | } else { 196 | setResultCancel() 197 | } 198 | } 199 | } 200 | 201 | /** 202 | * This method will be called when final result fot this provider is enabled. 203 | */ 204 | private fun handleResult() { 205 | activity.setImage(Uri.fromFile(mCameraFile)) 206 | } 207 | 208 | /** 209 | * Delete Camera file is exists 210 | */ 211 | override fun onFailure() { 212 | delete() 213 | } 214 | 215 | /** 216 | * Delete Camera File, If not required 217 | * 218 | * After Camera Image Crop/Compress Original File will not required 219 | */ 220 | fun delete() { 221 | mCameraFile?.delete() 222 | mCameraFile = null 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/provider/CompressionProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.provider 2 | 3 | import android.annotation.SuppressLint 4 | import android.graphics.Bitmap 5 | import android.net.Uri 6 | import android.os.AsyncTask 7 | import android.os.Bundle 8 | import com.github.dhaval2404.imagepicker.ImagePicker 9 | import com.github.dhaval2404.imagepicker.ImagePickerActivity 10 | import com.github.dhaval2404.imagepicker.util.ExifDataCopier 11 | import com.github.dhaval2404.imagepicker.util.FileUtil 12 | import com.github.dhaval2404.imagepicker.util.ImageUtil 13 | import java.io.File 14 | 15 | /** 16 | * Compress Selected/Captured Image 17 | * 18 | * @author Dhaval Patel 19 | * @version 1.0 20 | * @since 04 January 2019 21 | */ 22 | class CompressionProvider(activity: ImagePickerActivity) : BaseProvider(activity) { 23 | 24 | companion object { 25 | private val TAG = CompressionProvider::class.java.simpleName 26 | } 27 | 28 | private val mMaxWidth: Int 29 | private val mMaxHeight: Int 30 | private val mMaxFileSize: Long 31 | 32 | private val mFileDir: File 33 | 34 | init { 35 | val bundle = activity.intent.extras ?: Bundle() 36 | 37 | // Get Max Width/Height parameter from Intent 38 | mMaxWidth = bundle.getInt(ImagePicker.EXTRA_MAX_WIDTH, 0) 39 | mMaxHeight = bundle.getInt(ImagePicker.EXTRA_MAX_HEIGHT, 0) 40 | 41 | // Get Maximum Allowed file size 42 | mMaxFileSize = bundle.getLong(ImagePicker.EXTRA_IMAGE_MAX_SIZE, 0) 43 | 44 | // Get File Directory 45 | val fileDir = bundle.getString(ImagePicker.EXTRA_SAVE_DIRECTORY) 46 | mFileDir = getFileDir(fileDir) 47 | } 48 | 49 | /** 50 | * Check if compression should be enabled or not 51 | * 52 | * @return Boolean. True if Compression should be enabled else false. 53 | */ 54 | private fun isCompressEnabled(): Boolean { 55 | return mMaxFileSize > 0L 56 | } 57 | 58 | /** 59 | * Check if compression is required 60 | * @param file File object to apply Compression 61 | */ 62 | private fun isCompressionRequired(file: File): Boolean { 63 | val status = isCompressEnabled() && getSizeDiff(file) > 0L 64 | if (!status && mMaxWidth > 0 && mMaxHeight > 0) { 65 | // Check image resolution 66 | val resolution = FileUtil.getImageResolution(file) 67 | return resolution.first > mMaxWidth || resolution.second > mMaxHeight 68 | } 69 | return status 70 | } 71 | 72 | /** 73 | * Check if compression is required 74 | * @param uri Uri object to apply Compression 75 | */ 76 | fun isCompressionRequired(uri: Uri): Boolean { 77 | val status = isCompressEnabled() && getSizeDiff(uri) > 0L 78 | if (!status && mMaxWidth > 0 && mMaxHeight > 0) { 79 | // Check image resolution 80 | val resolution = FileUtil.getImageResolution(this, uri) 81 | return resolution.first > mMaxWidth || resolution.second > mMaxHeight 82 | } 83 | return status 84 | } 85 | 86 | private fun getSizeDiff(file: File): Long { 87 | return file.length() - mMaxFileSize 88 | } 89 | 90 | private fun getSizeDiff(uri: Uri): Long { 91 | val length = FileUtil.getImageSize(this, uri) 92 | return length - mMaxFileSize 93 | } 94 | 95 | /** 96 | * Compress given file if enabled. 97 | * 98 | * @param uri Uri to compress 99 | */ 100 | fun compress(uri: Uri) { 101 | startCompressionWorker(uri) 102 | } 103 | 104 | /** 105 | * Start Compression in Background 106 | */ 107 | @SuppressLint("StaticFieldLeak") 108 | private fun startCompressionWorker(uri: Uri) { 109 | object : AsyncTask() { 110 | override fun doInBackground(vararg params: Uri): File? { 111 | // Perform operation in background 112 | val file = FileUtil.getTempFile(this@CompressionProvider, params[0]) ?: return null 113 | return startCompression(file) 114 | } 115 | 116 | override fun onPostExecute(file: File?) { 117 | super.onPostExecute(file) 118 | if (file != null) { 119 | // Post Result 120 | handleResult(file) 121 | } else { 122 | // Post Error 123 | setError(com.github.dhaval2404.imagepicker.R.string.error_failed_to_compress_image) 124 | } 125 | } 126 | }.execute(uri) 127 | } 128 | 129 | /** 130 | * Check if compression required, And Apply compression until file size reach below Max Size. 131 | */ 132 | private fun startCompression(file: File): File? { 133 | var newFile: File? = null 134 | var attempt = 0 135 | var lastAttempt = 0 136 | do { 137 | // Delete file if exist, fill will be exist in second loop. 138 | newFile?.delete() 139 | 140 | newFile = applyCompression(file, attempt) 141 | if (newFile == null) { 142 | return if (attempt > 0) { 143 | applyCompression(file, lastAttempt) 144 | } else { 145 | null 146 | } 147 | } 148 | lastAttempt = attempt 149 | 150 | if (mMaxFileSize > 0) { 151 | val diff = getSizeDiff(newFile) 152 | // Log.i(TAG, "Size Diff:$diff") 153 | attempt += when { 154 | diff > 1024 * 1024 -> 3 155 | diff > 500 * 1024 -> 2 156 | else -> 1 157 | } 158 | } else { 159 | attempt++ 160 | } 161 | } while (isCompressionRequired(newFile!!)) 162 | 163 | // Copy Exif Data 164 | ExifDataCopier.copyExif(file, newFile) 165 | 166 | return newFile 167 | } 168 | 169 | /** 170 | * Compress the file 171 | */ 172 | private fun applyCompression(file: File, attempt: Int): File? { 173 | val resList = resolutionList() 174 | if (attempt >= resList.size) { 175 | return null 176 | } 177 | 178 | // Apply logic to get scaled bitmap resolution. 179 | val resolution = resList[attempt] 180 | var maxWidth = resolution[0] 181 | var maxHeight = resolution[1] 182 | 183 | if (mMaxWidth > 0 && mMaxHeight > 0) { 184 | if (maxWidth > mMaxWidth || maxHeight > mMaxHeight) { 185 | maxHeight = mMaxHeight 186 | maxWidth = mMaxWidth 187 | } 188 | } 189 | // Log.d(TAG, "maxWidth:$maxWidth, maxHeight:$maxHeight") 190 | 191 | // Check file format 192 | var format = Bitmap.CompressFormat.JPEG 193 | if (file.absolutePath.endsWith(".png")) { 194 | format = Bitmap.CompressFormat.PNG 195 | } 196 | 197 | val extension = FileUtil.getImageExtension(file) 198 | val compressFile: File? = FileUtil.getImageFile(fileDir = mFileDir, extension = extension) 199 | return if (compressFile != null) { 200 | ImageUtil.compressImage( 201 | file, maxWidth.toFloat(), maxHeight.toFloat(), 202 | format, compressFile.absolutePath 203 | ) 204 | } else { 205 | null 206 | } 207 | } 208 | 209 | /** 210 | * Image Resolution will be reduce with below parameters. 211 | * 212 | */ 213 | private fun resolutionList(): List { 214 | return listOf( 215 | intArrayOf(2448, 3264), // 8.0 Megapixel 216 | intArrayOf(2008, 3032), // 6.0 Megapixel 217 | intArrayOf(1944, 2580), // 5.0 Megapixel 218 | intArrayOf(1680, 2240), // 4.0 Megapixel 219 | intArrayOf(1536, 2048), // 3.0 Megapixel 220 | intArrayOf(1200, 1600), // 2.0 Megapixel 221 | intArrayOf(1024, 1392), // 1.3 Megapixel 222 | intArrayOf(960, 1280), // 1.0 Megapixel 223 | intArrayOf(768, 1024), // 0.7 Megapixel 224 | intArrayOf(600, 800), // 0.4 Megapixel 225 | intArrayOf(480, 640), // 0.3 Megapixel 226 | intArrayOf(240, 320), // 0.15 Megapixel 227 | intArrayOf(120, 160), // 0.08 Megapixel 228 | intArrayOf(60, 80), // 0.04 Megapixel 229 | intArrayOf(30, 40) // 0.02 Megapixel 230 | ) 231 | } 232 | 233 | /** 234 | * This method will be called when final result fot this provider is enabled. 235 | */ 236 | private fun handleResult(file: File) { 237 | activity.setCompressedImage(Uri.fromFile(file)) 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/provider/CropProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.provider 2 | 3 | import android.app.Activity 4 | import android.content.ActivityNotFoundException 5 | import android.content.Intent 6 | import android.net.Uri 7 | import android.os.Bundle 8 | import android.util.Log 9 | import com.github.dhaval2404.imagepicker.ImagePicker 10 | import com.github.dhaval2404.imagepicker.ImagePickerActivity 11 | import com.github.dhaval2404.imagepicker.R 12 | import com.github.dhaval2404.imagepicker.util.FileUtil 13 | import com.yalantis.ucrop.UCrop 14 | import java.io.File 15 | import java.io.IOException 16 | 17 | /** 18 | * Crop Selected/Captured Image 19 | * 20 | * @author Dhaval Patel 21 | * @version 1.0 22 | * @since 04 January 2019 23 | */ 24 | class CropProvider(activity: ImagePickerActivity) : BaseProvider(activity) { 25 | 26 | companion object { 27 | private val TAG = CropProvider::class.java.simpleName 28 | 29 | /** 30 | * Key to Save/Retrieve Crop File state 31 | */ 32 | private const val STATE_CROP_FILE = "state.crop_file" 33 | } 34 | 35 | private val mMaxWidth: Int 36 | private val mMaxHeight: Int 37 | 38 | private val mCrop: Boolean 39 | private val mCropAspectX: Float 40 | private val mCropAspectY: Float 41 | private var mCropImageFile: File? = null 42 | private val mFileDir: File 43 | 44 | init { 45 | val bundle = activity.intent.extras ?: Bundle() 46 | 47 | // Get Max Width/Height parameter from Intent 48 | mMaxWidth = bundle.getInt(ImagePicker.EXTRA_MAX_WIDTH, 0) 49 | mMaxHeight = bundle.getInt(ImagePicker.EXTRA_MAX_HEIGHT, 0) 50 | 51 | // Get Crop Aspect Ratio parameter from Intent 52 | mCrop = bundle.getBoolean(ImagePicker.EXTRA_CROP, false) 53 | mCropAspectX = bundle.getFloat(ImagePicker.EXTRA_CROP_X, 0f) 54 | mCropAspectY = bundle.getFloat(ImagePicker.EXTRA_CROP_Y, 0f) 55 | 56 | // Get File Directory 57 | val fileDir = bundle.getString(ImagePicker.EXTRA_SAVE_DIRECTORY) 58 | mFileDir = getFileDir(fileDir) 59 | } 60 | 61 | /** 62 | * Save CameraProvider state 63 | * 64 | * mCropImageFile will lose its state when activity is recreated on 65 | * Orientation change or for Low memory device. 66 | * 67 | * Here, We Will save its state for later use 68 | * 69 | * Note: To produce this scenario, enable "Don't keep activities" from developer options 70 | */ 71 | override fun onSaveInstanceState(outState: Bundle) { 72 | // Save crop file 73 | outState.putSerializable(STATE_CROP_FILE, mCropImageFile) 74 | } 75 | 76 | /** 77 | * Retrieve CropProvider state 78 | */ 79 | override fun onRestoreInstanceState(savedInstanceState: Bundle?) { 80 | // Restore crop file 81 | mCropImageFile = savedInstanceState?.getSerializable(STATE_CROP_FILE) as File? 82 | } 83 | 84 | /** 85 | * Check if crop should be enabled or not 86 | * 87 | * @return Boolean. True if Crop should be enabled else false. 88 | */ 89 | fun isCropEnabled() = mCrop 90 | 91 | /** 92 | * Start Crop Activity 93 | */ 94 | fun startIntent(uri: Uri) { 95 | cropImage(uri) 96 | } 97 | 98 | /** 99 | * @param uri Uri to be cropped 100 | * @throws IOException if failed to crop image 101 | */ 102 | @Throws(IOException::class) 103 | private fun cropImage(uri: Uri) { 104 | val extension = FileUtil.getImageExtension(uri) 105 | mCropImageFile = FileUtil.getImageFile(fileDir = mFileDir, extension = extension) 106 | 107 | if (mCropImageFile == null || !mCropImageFile!!.exists()) { 108 | Log.e(TAG, "Failed to create crop image file") 109 | setError(R.string.error_failed_to_crop_image) 110 | return 111 | } 112 | 113 | val options = UCrop.Options() 114 | options.setCompressionFormat(FileUtil.getCompressFormat(extension)) 115 | 116 | val uCrop = UCrop.of(uri, Uri.fromFile(mCropImageFile)) 117 | .withOptions(options) 118 | 119 | if (mCropAspectX > 0 && mCropAspectY > 0) { 120 | uCrop.withAspectRatio(mCropAspectX, mCropAspectY) 121 | } 122 | 123 | if (mMaxWidth > 0 && mMaxHeight > 0) { 124 | uCrop.withMaxResultSize(mMaxWidth, mMaxHeight) 125 | } 126 | 127 | try { 128 | uCrop.start(activity, UCrop.REQUEST_CROP) 129 | } catch (ex: ActivityNotFoundException) { 130 | setError( 131 | "uCrop not specified in manifest file." + 132 | "Add UCropActivity in Manifest" + 133 | "" 137 | ) 138 | ex.printStackTrace() 139 | } 140 | } 141 | 142 | /** 143 | * Handle Crop Intent Activity Result 144 | * 145 | * @param requestCode It must be {@link UCrop#REQUEST_CROP} 146 | * @param resultCode For success it should be {@link Activity#RESULT_OK} 147 | * @param data Result Intent 148 | */ 149 | @Suppress("UNUSED_PARAMETER") 150 | fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 151 | if (requestCode == UCrop.REQUEST_CROP) { 152 | if (resultCode == Activity.RESULT_OK) { 153 | handleResult(mCropImageFile) 154 | } else { 155 | setResultCancel() 156 | } 157 | } 158 | } 159 | 160 | /** 161 | * This method will be called when final result fot this provider is enabled. 162 | * 163 | * @param file cropped file 164 | */ 165 | private fun handleResult(file: File?) { 166 | if (file != null) { 167 | activity.setCropImage(Uri.fromFile(file)) 168 | } else { 169 | setError(R.string.error_failed_to_crop_image) 170 | } 171 | } 172 | 173 | /** 174 | * Handle Crop Failed 175 | */ 176 | override fun onFailure() { 177 | delete() 178 | } 179 | 180 | /** 181 | * Delete Crop File, If not required 182 | * 183 | * After Image Compression, Crop File will not required 184 | */ 185 | fun delete() { 186 | mCropImageFile?.delete() 187 | mCropImageFile = null 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/provider/GalleryProvider.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.provider 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.net.Uri 6 | import android.os.Bundle 7 | import com.github.dhaval2404.imagepicker.ImagePicker 8 | import com.github.dhaval2404.imagepicker.ImagePickerActivity 9 | import com.github.dhaval2404.imagepicker.R 10 | import com.github.dhaval2404.imagepicker.util.IntentUtils 11 | 12 | /** 13 | * Select image from Storage 14 | * 15 | * @author Dhaval Patel 16 | * @version 1.0 17 | * @since 04 January 2019 18 | */ 19 | class GalleryProvider(activity: ImagePickerActivity) : 20 | BaseProvider(activity) { 21 | 22 | companion object { 23 | private const val GALLERY_INTENT_REQ_CODE = 4261 24 | } 25 | 26 | // Mime types restrictions for gallery. By default all mime types are valid 27 | private val mimeTypes: Array 28 | 29 | init { 30 | val bundle = activity.intent.extras ?: Bundle() 31 | 32 | // Get MIME types 33 | mimeTypes = bundle.getStringArray(ImagePicker.EXTRA_MIME_TYPES) ?: emptyArray() 34 | } 35 | 36 | /** 37 | * Start Gallery Capture Intent 38 | */ 39 | fun startIntent() { 40 | startGalleryIntent() 41 | } 42 | 43 | /** 44 | * Start Gallery Intent 45 | */ 46 | private fun startGalleryIntent() { 47 | val galleryIntent = IntentUtils.getGalleryIntent(activity, mimeTypes) 48 | activity.startActivityForResult(galleryIntent, GALLERY_INTENT_REQ_CODE) 49 | } 50 | 51 | /** 52 | * Handle Gallery Intent Activity Result 53 | * 54 | * @param requestCode It must be {@link GalleryProvider#GALLERY_INTENT_REQ_CODE} 55 | * @param resultCode For success it should be {@link Activity#RESULT_OK} 56 | * @param data Result Intent 57 | */ 58 | fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 59 | if (requestCode == GALLERY_INTENT_REQ_CODE) { 60 | if (resultCode == Activity.RESULT_OK) { 61 | handleResult(data) 62 | } else { 63 | setResultCancel() 64 | } 65 | } 66 | } 67 | 68 | /** 69 | * This method will be called when final result fot this provider is enabled. 70 | */ 71 | private fun handleResult(data: Intent?) { 72 | val uri = data?.data 73 | if (uri != null) { 74 | takePersistableUriPermission(uri) 75 | activity.setImage(uri) 76 | } else { 77 | setError(R.string.error_failed_pick_gallery_image) 78 | } 79 | } 80 | 81 | /** 82 | * Take a persistable URI permission grant that has been offered. Once 83 | * taken, the permission grant will be remembered across device reboots. 84 | */ 85 | private fun takePersistableUriPermission(uri: Uri) { 86 | contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/DialogHelper.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.content.Context 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import androidx.appcompat.app.AlertDialog 7 | import com.github.dhaval2404.imagepicker.R 8 | import com.github.dhaval2404.imagepicker.constant.ImageProvider 9 | import com.github.dhaval2404.imagepicker.listener.DismissListener 10 | import com.github.dhaval2404.imagepicker.listener.ResultListener 11 | 12 | /** 13 | * Show Dialog 14 | * 15 | * @author Dhaval Patel 16 | * @version 1.0 17 | * @since 04 January 2018 18 | */ 19 | internal object DialogHelper { 20 | 21 | /** 22 | * Show Image Provide Picker Dialog. This will streamline the code to pick/capture image 23 | * 24 | */ 25 | fun showChooseAppDialog( 26 | context: Context, 27 | listener: ResultListener, 28 | dismissListener: DismissListener? 29 | ) { 30 | val layoutInflater = LayoutInflater.from(context) 31 | val customView = layoutInflater.inflate(R.layout.dialog_choose_app, null) 32 | 33 | val dialog = AlertDialog.Builder(context) 34 | .setTitle(R.string.title_choose_image_provider) 35 | .setView(customView) 36 | .setOnCancelListener { 37 | listener.onResult(null) 38 | } 39 | .setNegativeButton(R.string.action_cancel) { _, _ -> 40 | listener.onResult(null) 41 | } 42 | .setOnDismissListener { 43 | dismissListener?.onDismiss() 44 | } 45 | .show() 46 | 47 | // Handle Camera option click 48 | customView.findViewById(R.id.lytCameraPick).setOnClickListener { 49 | listener.onResult(ImageProvider.CAMERA) 50 | dialog.dismiss() 51 | } 52 | 53 | // Handle Gallery option click 54 | customView.findViewById(R.id.lytGalleryPick).setOnClickListener { 55 | listener.onResult(ImageProvider.GALLERY) 56 | dialog.dismiss() 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/ExifDataCopier.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.util.Log 4 | import androidx.exifinterface.media.ExifInterface 5 | import java.io.File 6 | 7 | /** 8 | * This file was taken from 9 | * https://raw.githubusercontent.com/flutter/plugins/05879a3a4d8e582702227731ccdcf8b115f6b83d/packages/image_picker/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java 10 | */ 11 | object ExifDataCopier { 12 | 13 | fun copyExif(filePathOri: File, filePathDest: File) { 14 | try { 15 | val oldExif = ExifInterface(filePathOri) 16 | val newExif = ExifInterface(filePathDest) 17 | val attributes: List = listOf( 18 | "FNumber", 19 | "ExposureTime", 20 | "ISOSpeedRatings", 21 | "GPSAltitude", 22 | "GPSAltitudeRef", 23 | "FocalLength", 24 | "GPSDateStamp", 25 | "WhiteBalance", 26 | "GPSProcessingMethod", 27 | "GPSTimeStamp", 28 | "DateTime", 29 | "Flash", 30 | "GPSLatitude", 31 | "GPSLatitudeRef", 32 | "GPSLongitude", 33 | "GPSLongitudeRef", 34 | "Make", 35 | "Model", 36 | "Orientation" 37 | ) 38 | for (attribute in attributes) { 39 | setIfNotNull(oldExif, newExif, attribute) 40 | } 41 | newExif.saveAttributes() 42 | } catch (ex: Exception) { 43 | Log.e("ExifDataCopier", "Error preserving Exif data on selected image: $ex") 44 | } 45 | } 46 | 47 | private fun setIfNotNull(oldExif: ExifInterface, newExif: ExifInterface, property: String) { 48 | if (oldExif.getAttribute(property) != null) { 49 | newExif.setAttribute(property, oldExif.getAttribute(property)) 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/FileUriUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.content.ContentUris 4 | import android.content.Context 5 | import android.database.Cursor 6 | import android.net.Uri 7 | import android.os.Build 8 | import android.os.Environment 9 | import android.provider.DocumentsContract 10 | import android.provider.MediaStore 11 | import java.io.File 12 | import java.io.FileOutputStream 13 | import java.io.IOException 14 | import java.io.InputStream 15 | import java.io.OutputStream 16 | 17 | /** 18 | * This file was taken from 19 | * https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8 20 | * 21 | * Later on it was modified from the below resource: 22 | * https://raw.githubusercontent.com/iPaulPro/aFileChooser/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java 23 | * https://raw.githubusercontent.com/iPaulPro/aFileChooser/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java 24 | */ 25 | 26 | object FileUriUtils { 27 | 28 | fun getRealPath(context: Context, uri: Uri): String? { 29 | var path = getPathFromLocalUri(context, uri) 30 | if (path == null) { 31 | path = getPathFromRemoteUri(context, uri) 32 | } 33 | return path 34 | } 35 | 36 | private fun getPathFromLocalUri(context: Context, uri: Uri): String? { 37 | val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT 38 | 39 | // DocumentProvider 40 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 41 | // ExternalStorageProvider 42 | if (isExternalStorageDocument(uri)) { 43 | val docId = DocumentsContract.getDocumentId(uri) 44 | val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() 45 | val type = split[0] 46 | 47 | // This is for checking Main Memory 48 | return if ("primary".equals(type, ignoreCase = true)) { 49 | if (split.size > 1) { 50 | Environment.getExternalStorageDirectory().toString() + "/" + split[1] 51 | } else { 52 | Environment.getExternalStorageDirectory().toString() + "/" 53 | } 54 | // This is for checking SD Card 55 | } else { 56 | val path = "storage" + "/" + docId.replace(":", "/") 57 | if (File(path).exists()) { 58 | path 59 | } else { 60 | "/storage/sdcard/" + split[1] 61 | } 62 | } 63 | } else if (isDownloadsDocument(uri)) { 64 | return getDownloadDocument(context, uri) 65 | } else if (isMediaDocument(uri)) { 66 | return getMediaDocument(context, uri) 67 | } 68 | } else if ("content".equals(uri.scheme!!, ignoreCase = true)) { 69 | // Return the remote address 70 | return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn( 71 | context, 72 | uri, 73 | null, 74 | null 75 | ) 76 | } else if ("file".equals(uri.scheme!!, ignoreCase = true)) { 77 | return uri.path 78 | } 79 | return null 80 | } 81 | 82 | private fun getDataColumn( 83 | context: Context, 84 | uri: Uri?, 85 | selection: String?, 86 | selectionArgs: Array? 87 | ): String? { 88 | 89 | var cursor: Cursor? = null 90 | val column = "_data" 91 | val projection = arrayOf(column) 92 | 93 | try { 94 | cursor = 95 | context.contentResolver.query(uri!!, projection, selection, selectionArgs, null) 96 | if (cursor != null && cursor.moveToFirst()) { 97 | val index = cursor.getColumnIndexOrThrow(column) 98 | return cursor.getString(index) 99 | } 100 | } catch (ex: Exception) { 101 | ex.printStackTrace() 102 | } finally { 103 | cursor?.close() 104 | } 105 | return null 106 | } 107 | 108 | private fun getDownloadDocument(context: Context, uri: Uri): String? { 109 | val fileName = getFilePath(context, uri) 110 | if (fileName != null) { 111 | val path = 112 | Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName 113 | if (File(path).exists()) { 114 | return path 115 | } 116 | } 117 | 118 | var id = DocumentsContract.getDocumentId(uri) 119 | if (id.contains(":")) { 120 | id = id.split(":")[1] 121 | } 122 | val contentUri = ContentUris.withAppendedId( 123 | Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id) 124 | ) 125 | return getDataColumn(context, contentUri, null, null) 126 | } 127 | 128 | private fun getMediaDocument(context: Context, uri: Uri): String? { 129 | val docId = DocumentsContract.getDocumentId(uri) 130 | val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() 131 | val type = split[0] 132 | 133 | var contentUri: Uri? = null 134 | if ("image" == type) { 135 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI 136 | } else if ("video" == type) { 137 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI 138 | } else if ("audio" == type) { 139 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 140 | } 141 | 142 | val selection = "_id=?" 143 | val selectionArgs = arrayOf(split[1]) 144 | 145 | return getDataColumn(context, contentUri, selection, selectionArgs) 146 | } 147 | 148 | private fun getFilePath(context: Context, uri: Uri): String? { 149 | 150 | var cursor: Cursor? = null 151 | val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) 152 | 153 | try { 154 | cursor = context.contentResolver.query(uri, projection, null, null, null) 155 | if (cursor != null && cursor.moveToFirst()) { 156 | val index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME) 157 | return cursor.getString(index) 158 | } 159 | } finally { 160 | cursor?.close() 161 | } 162 | return null 163 | } 164 | 165 | private fun getPathFromRemoteUri(context: Context, uri: Uri): String? { 166 | // The code below is why Java now has try-with-resources and the Files utility. 167 | var file: File? = null 168 | var inputStream: InputStream? = null 169 | var outputStream: OutputStream? = null 170 | var success = false 171 | try { 172 | val extension = FileUtil.getImageExtension(uri) 173 | inputStream = context.contentResolver.openInputStream(uri) 174 | file = FileUtil.getImageFile(context.cacheDir, extension) 175 | if (file == null) return null 176 | outputStream = FileOutputStream(file) 177 | if (inputStream != null) { 178 | inputStream.copyTo(outputStream, bufferSize = 4 * 1024) 179 | success = true 180 | } 181 | } catch (ignored: IOException) { 182 | } finally { 183 | try { 184 | inputStream?.close() 185 | } catch (ignored: IOException) { 186 | } 187 | 188 | try { 189 | outputStream?.close() 190 | } catch (ignored: IOException) { 191 | // If closing the output stream fails, we cannot be sure that the 192 | // target file was written in full. Flushing the stream merely moves 193 | // the bytes into the OS, not necessarily to the file. 194 | success = false 195 | } 196 | } 197 | return if (success) file!!.path else null 198 | } 199 | 200 | /** 201 | * @param uri The Uri to check. 202 | * @return Whether the Uri authority is ExternalStorageProvider. 203 | */ 204 | private fun isExternalStorageDocument(uri: Uri): Boolean { 205 | return "com.android.externalstorage.documents" == uri.authority 206 | } 207 | 208 | /** 209 | * @param uri The Uri to check. 210 | * @return Whether the Uri authority is DownloadsProvider. 211 | */ 212 | private fun isDownloadsDocument(uri: Uri): Boolean { 213 | return "com.android.providers.downloads.documents" == uri.authority 214 | } 215 | 216 | /** 217 | * @param uri The Uri to check. 218 | * @return Whether the Uri authority is MediaProvider. 219 | */ 220 | private fun isMediaDocument(uri: Uri): Boolean { 221 | return "com.android.providers.media.documents" == uri.authority 222 | } 223 | 224 | /** 225 | * @param uri The Uri to check. 226 | * @return Whether the Uri authority is Google Photos. 227 | */ 228 | private fun isGooglePhotosUri(uri: Uri): Boolean { 229 | return "com.google.android.apps.photos.content" == uri.authority 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/FileUtil.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.content.Context 4 | import android.graphics.Bitmap 5 | import android.graphics.BitmapFactory 6 | import android.net.Uri 7 | import android.os.Build 8 | import android.os.StatFs 9 | import androidx.documentfile.provider.DocumentFile 10 | import java.io.File 11 | import java.io.FileInputStream 12 | import java.io.FileOutputStream 13 | import java.io.IOException 14 | import java.text.SimpleDateFormat 15 | import java.util.Date 16 | import java.util.Locale 17 | 18 | /** 19 | * File Utility Methods 20 | * 21 | * @author Dhaval Patel 22 | * @version 1.0 23 | * @since 04 January 2019 24 | */ 25 | object FileUtil { 26 | 27 | /** 28 | * Get Image File 29 | * 30 | * Default it will take Camera folder as it's directory 31 | * 32 | * @param fileDir File Folder in which file needs tobe created. 33 | * @param extension String Image file extension. 34 | * @return Return Empty file to store camera image. 35 | * @throws IOException if permission denied of failed to create new file. 36 | */ 37 | fun getImageFile(fileDir: File, extension: String? = null): File? { 38 | try { 39 | // Create an image file name 40 | val ext = extension ?: ".jpg" 41 | val fileName = getFileName() 42 | val imageFileName = "$fileName$ext" 43 | 44 | // Create Directory If not exist 45 | if (!fileDir.exists()) fileDir.mkdirs() 46 | 47 | // Create File Object 48 | val file = File(fileDir, imageFileName) 49 | 50 | // Create empty file 51 | file.createNewFile() 52 | 53 | return file 54 | } catch (ex: IOException) { 55 | ex.printStackTrace() 56 | return null 57 | } 58 | } 59 | 60 | private fun getFileName() = "IMG_${getTimestamp()}" 61 | // private fun getFileName() = "IMAGE_PICKER" 62 | 63 | /** 64 | * Get Current Time in yyyyMMdd HHmmssSSS format 65 | * 66 | * 2019/01/30 10:30:20 000 67 | * E.g. 20190130_103020000 68 | */ 69 | private fun getTimestamp(): String { 70 | val timeFormat = "yyyyMMdd_HHmmssSSS" 71 | return SimpleDateFormat(timeFormat, Locale.getDefault()).format(Date()) 72 | } 73 | 74 | /** 75 | * Get Free Space size 76 | * @param file directory object to check free space. 77 | */ 78 | fun getFreeSpace(file: File): Long { 79 | val stat = StatFs(file.path) 80 | val availBlocks = stat.availableBlocksLong 81 | val blockSize = stat.blockSizeLong 82 | return availBlocks * blockSize 83 | } 84 | 85 | /** 86 | * Get Image Width & Height from Uri 87 | * 88 | * @param uri Uri to get Image Size 89 | * @return Int Array, Index 0 has width and Index 1 has height 90 | */ 91 | fun getImageResolution(context: Context, uri: Uri): Pair { 92 | val options = BitmapFactory.Options() 93 | options.inJustDecodeBounds = true 94 | val stream = context.contentResolver.openInputStream(uri) 95 | BitmapFactory.decodeStream(stream, null, options) 96 | return Pair(options.outWidth, options.outHeight) 97 | } 98 | 99 | /** 100 | * Get Image Width & Height from File 101 | * 102 | * @param file File to get Image Size 103 | * @return Int Array, Index 0 has width and Index 1 has height 104 | */ 105 | fun getImageResolution(file: File): Pair { 106 | val options = BitmapFactory.Options() 107 | options.inJustDecodeBounds = true 108 | BitmapFactory.decodeFile(file.absolutePath, options) 109 | return Pair(options.outWidth, options.outHeight) 110 | } 111 | 112 | /** 113 | * Get Image File Size 114 | * 115 | * @param uri Uri to get Image Size 116 | * @return Int Image File Size 117 | */ 118 | fun getImageSize(context: Context, uri: Uri): Long { 119 | return getDocumentFile(context, uri)?.length() ?: 0 120 | } 121 | 122 | /** 123 | * Create copy of Uri into application specific local path 124 | * 125 | * @param context Application Context 126 | * @param uri Source Uri 127 | * @return File return copy of Uri object 128 | */ 129 | fun getTempFile(context: Context, uri: Uri): File? { 130 | try { 131 | val destination = File(context.cacheDir, "image_picker.png") 132 | 133 | val parcelFileDescriptor = context.contentResolver.openFileDescriptor(uri, "r") 134 | val fileDescriptor = parcelFileDescriptor?.fileDescriptor ?: return null 135 | 136 | val src = FileInputStream(fileDescriptor).channel 137 | val dst = FileOutputStream(destination).channel 138 | dst.transferFrom(src, 0, src.size()) 139 | src.close() 140 | dst.close() 141 | 142 | return destination 143 | } catch (ex: IOException) { 144 | ex.printStackTrace() 145 | } 146 | return null 147 | } 148 | 149 | /** 150 | * Get DocumentFile from Uri 151 | * 152 | * @param context Application Context 153 | * @param uri Source Uri 154 | * @return DocumentFile return DocumentFile from Uri 155 | */ 156 | fun getDocumentFile(context: Context, uri: Uri): DocumentFile? { 157 | var file: DocumentFile? = null 158 | if (isFileUri(uri)) { 159 | val path = FileUriUtils.getRealPath(context, uri) 160 | if (path != null) { 161 | file = DocumentFile.fromFile(File(path)) 162 | } 163 | } else { 164 | file = DocumentFile.fromSingleUri(context, uri) 165 | } 166 | return file 167 | } 168 | 169 | /** 170 | * Get Bitmap Compress Format 171 | * 172 | * @param extension Image File Extension 173 | * @return Bitmap CompressFormat 174 | */ 175 | @Suppress("DEPRECATION") 176 | fun getCompressFormat(extension: String): Bitmap.CompressFormat { 177 | return when { 178 | extension.contains("png", ignoreCase = true) -> Bitmap.CompressFormat.PNG 179 | extension.contains("webp", ignoreCase = true) -> { 180 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 181 | Bitmap.CompressFormat.WEBP_LOSSLESS 182 | } else { 183 | Bitmap.CompressFormat.WEBP 184 | } 185 | } 186 | else -> Bitmap.CompressFormat.JPEG 187 | } 188 | } 189 | 190 | /** 191 | * Get Image Extension i.e. .png, .jpg 192 | * 193 | * @return extension of image with dot, or default .jpg if it none. 194 | */ 195 | fun getImageExtension(file: File): String { 196 | return getImageExtension(Uri.fromFile(file)) 197 | } 198 | 199 | /** 200 | * Get Image Extension i.e. .png, .jpg 201 | * 202 | * @return extension of image with dot, or default .jpg if it none. 203 | */ 204 | fun getImageExtension(uriImage: Uri): String { 205 | var extension: String? = null 206 | 207 | try { 208 | val imagePath = uriImage.path 209 | if (imagePath != null && imagePath.lastIndexOf(".") != -1) { 210 | extension = imagePath.substring(imagePath.lastIndexOf(".") + 1) 211 | } 212 | } catch (e: Exception) { 213 | extension = null 214 | } 215 | 216 | if (extension == null || extension.isEmpty()) { 217 | // default extension for matches the previous behavior of the plugin 218 | extension = "jpg" 219 | } 220 | 221 | return ".$extension" 222 | } 223 | 224 | /** 225 | * Check if provided URI is backed by File 226 | * 227 | * @return Boolean, True if Uri is local file object else return false 228 | */ 229 | private fun isFileUri(uri: Uri): Boolean { 230 | return "file".equals(uri.scheme, ignoreCase = true) 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/ImageUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016, The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.dhaval2404.imagepicker.util 17 | 18 | import android.graphics.Bitmap 19 | import android.graphics.BitmapFactory 20 | import android.graphics.Canvas 21 | import android.graphics.Matrix 22 | import android.graphics.Paint 23 | import android.os.Build 24 | import java.io.File 25 | import java.io.FileOutputStream 26 | import java.io.IOException 27 | 28 | /** 29 | * Created on : June 18, 2016 30 | * Author : zetbaitsu 31 | * Name : Zetra 32 | * GitHub : https://github.com/zetbaitsu 33 | * 34 | * For More Info Visit: https://github.com/zetbaitsu/Compressor 35 | */ 36 | object ImageUtil { 37 | 38 | @Throws(IOException::class) 39 | fun compressImage( 40 | imageFile: File, 41 | reqWidth: Float, 42 | reqHeight: Float, 43 | compressFormat: Bitmap.CompressFormat, 44 | destinationPath: String 45 | ): File { 46 | var fileOutputStream: FileOutputStream? = null 47 | val file = File(destinationPath).parentFile 48 | if (file?.exists() == false) { 49 | file.mkdirs() 50 | } 51 | try { 52 | fileOutputStream = FileOutputStream(destinationPath) 53 | // write the compressed bitmap at the destination specified by destinationPath. 54 | decodeSampledBitmapFromFile(imageFile, reqWidth, reqHeight)?.compress( 55 | compressFormat, 56 | 100, 57 | fileOutputStream 58 | ) 59 | } finally { 60 | if (fileOutputStream != null) { 61 | fileOutputStream.flush() 62 | fileOutputStream.close() 63 | } 64 | } 65 | 66 | return File(destinationPath) 67 | } 68 | 69 | @Throws(IOException::class) 70 | private fun decodeSampledBitmapFromFile( 71 | imageFile: File, 72 | reqWidth: Float, 73 | reqHeight: Float 74 | ): Bitmap? { 75 | // First decode with inJustDecodeBounds=true to check dimensions 76 | 77 | val options = BitmapFactory.Options() 78 | options.inJustDecodeBounds = true 79 | var bmp: Bitmap? = BitmapFactory.decodeFile(imageFile.absolutePath, options) 80 | 81 | var actualHeight = options.outHeight 82 | var actualWidth = options.outWidth 83 | 84 | var imgRatio = actualWidth.toFloat() / actualHeight.toFloat() 85 | val maxRatio = reqWidth / reqHeight 86 | 87 | if (actualHeight > reqHeight || actualWidth > reqWidth) { 88 | // If Height is greater 89 | if (imgRatio < maxRatio) { 90 | imgRatio = reqHeight / actualHeight 91 | actualWidth = (imgRatio * actualWidth).toInt() 92 | actualHeight = reqHeight.toInt() 93 | } // If Width is greater 94 | else if (imgRatio > maxRatio) { 95 | imgRatio = reqWidth / actualWidth 96 | actualHeight = (imgRatio * actualHeight).toInt() 97 | actualWidth = reqWidth.toInt() 98 | } else { 99 | actualHeight = reqHeight.toInt() 100 | actualWidth = reqWidth.toInt() 101 | } 102 | } 103 | 104 | // Calculate inSampleSize 105 | options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight) 106 | options.inJustDecodeBounds = false 107 | 108 | if (bmp != null && canUseForInBitmap(bmp, options)) { 109 | // inBitmap only works with mutable bitmaps, so force the decoder to 110 | // return mutable bitmaps. 111 | options.inMutable = true 112 | options.inBitmap = bmp 113 | } 114 | options.inTempStorage = ByteArray(16 * 1024) 115 | 116 | try { 117 | bmp = BitmapFactory.decodeFile(imageFile.absolutePath, options) 118 | } catch (exception: OutOfMemoryError) { 119 | exception.printStackTrace() 120 | } 121 | 122 | var scaledBitmap: Bitmap? = null 123 | try { 124 | scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888) 125 | } catch (exception: OutOfMemoryError) { 126 | exception.printStackTrace() 127 | } 128 | 129 | val ratioX = actualWidth / options.outWidth.toFloat() 130 | val ratioY = actualHeight / options.outHeight.toFloat() 131 | val middleX = actualWidth / 2.0f 132 | val middleY = actualHeight / 2.0f 133 | 134 | val scaleMatrix = Matrix() 135 | scaleMatrix.setScale(ratioX, ratioY, middleX, middleY) 136 | 137 | val canvas = Canvas(scaledBitmap!!) 138 | canvas.setMatrix(scaleMatrix) 139 | canvas.drawBitmap( 140 | bmp!!, middleX - bmp.width / 2, 141 | middleY - bmp.height / 2, Paint(Paint.FILTER_BITMAP_FLAG) 142 | ) 143 | bmp.recycle() 144 | 145 | val matrix = Matrix() 146 | scaledBitmap = Bitmap.createBitmap( 147 | scaledBitmap, 0, 0, scaledBitmap.width, 148 | scaledBitmap.height, matrix, true 149 | ) 150 | 151 | return scaledBitmap 152 | } 153 | 154 | private fun calculateInSampleSize( 155 | options: BitmapFactory.Options, 156 | reqWidth: Int, 157 | reqHeight: Int 158 | ): Int { 159 | // Raw height and width of image 160 | val height = options.outHeight 161 | val width = options.outWidth 162 | var inSampleSize = 1 163 | 164 | if (height > reqHeight || width > reqWidth) { 165 | val halfHeight: Int = height / 2 166 | val halfWidth: Int = width / 2 167 | 168 | // Calculate the largest inSampleSize value that is a power of 2 and keeps both 169 | // height and width larger than the requested height and width. 170 | while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) { 171 | inSampleSize *= 2 172 | } 173 | } 174 | 175 | return inSampleSize 176 | } 177 | 178 | /** 179 | * Ref: https://developer.android.com/topic/performance/graphics/manage-memory#kotlin 180 | */ 181 | private fun canUseForInBitmap( 182 | candidate: Bitmap, 183 | targetOptions: BitmapFactory.Options 184 | ): Boolean { 185 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 186 | // From Android 4.4 (KitKat) onward we can re-use if the byte size of 187 | // the new bitmap is smaller than the reusable bitmap candidate 188 | // allocation byte count. 189 | val width: Int = targetOptions.outWidth / targetOptions.inSampleSize 190 | val height: Int = targetOptions.outHeight / targetOptions.inSampleSize 191 | val byteCount: Int = width * height * getBytesPerPixel(candidate.config) 192 | byteCount <= candidate.allocationByteCount 193 | } else { 194 | // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 195 | candidate.width == targetOptions.outWidth && 196 | candidate.height == targetOptions.outHeight && 197 | targetOptions.inSampleSize == 1 198 | } 199 | } 200 | 201 | /** 202 | * A helper function to return the byte usage per pixel of a bitmap based on its configuration. 203 | */ 204 | @Suppress("DEPRECATION") 205 | private fun getBytesPerPixel(config: Bitmap.Config): Int { 206 | return when (config) { 207 | Bitmap.Config.ARGB_8888 -> 4 208 | Bitmap.Config.RGB_565, Bitmap.Config.ARGB_4444 -> 2 209 | Bitmap.Config.ALPHA_8 -> 1 210 | else -> 1 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/IntentUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.net.Uri 6 | import android.os.Build 7 | import android.provider.MediaStore 8 | import androidx.core.content.FileProvider 9 | import androidx.documentfile.provider.DocumentFile 10 | import com.github.dhaval2404.imagepicker.R 11 | import java.io.File 12 | 13 | /** 14 | * Get Gallery/Camera Intent 15 | * 16 | * @author Dhaval Patel 17 | * @version 1.0 18 | * @since 04 January 2018 19 | */ 20 | object IntentUtils { 21 | 22 | /** 23 | * @return Intent Gallery Intent 24 | */ 25 | @JvmStatic 26 | fun getGalleryIntent(context: Context, mimeTypes: Array): Intent { 27 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 28 | val intent = getGalleryDocumentIntent(mimeTypes) 29 | if (intent.resolveActivity(context.packageManager) != null) { 30 | return intent 31 | } 32 | } 33 | return getLegacyGalleryPickIntent(mimeTypes) 34 | } 35 | 36 | /** 37 | * Ref: https://developer.android.com/reference/android/content/Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION 38 | * 39 | * @return Intent Gallery Document Intent 40 | */ 41 | private fun getGalleryDocumentIntent(mimeTypes: Array): Intent { 42 | // Show Document Intent 43 | val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).applyImageTypes(mimeTypes) 44 | intent.addCategory(Intent.CATEGORY_OPENABLE) 45 | intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) 46 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 47 | intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION) 48 | return intent 49 | } 50 | 51 | /** 52 | * @return Intent Gallery Pick Intent 53 | */ 54 | private fun getLegacyGalleryPickIntent(mimeTypes: Array): Intent { 55 | // Show Gallery Intent, Will open google photos 56 | return Intent(Intent.ACTION_PICK).applyImageTypes(mimeTypes) 57 | } 58 | 59 | private fun Intent.applyImageTypes(mimeTypes: Array): Intent { 60 | // Apply filter to show image only in intent 61 | type = "image/*" 62 | if (mimeTypes.isNotEmpty()) { 63 | putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) 64 | } 65 | return this 66 | } 67 | 68 | /** 69 | * @return Intent Camera Intent 70 | */ 71 | @JvmStatic 72 | fun getCameraIntent(context: Context, file: File): Intent? { 73 | val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 74 | 75 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 76 | // authority = com.github.dhaval2404.imagepicker.provider 77 | val authority = 78 | context.packageName + context.getString(R.string.image_picker_provider_authority_suffix) 79 | val photoURI = FileProvider.getUriForFile(context, authority, file) 80 | intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) 81 | } else { 82 | intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)) 83 | } 84 | 85 | return intent 86 | } 87 | 88 | /** 89 | * Check if Camera App is available or not 90 | * 91 | * @return true if Camera App is Available else return false 92 | */ 93 | @JvmStatic 94 | fun isCameraAppAvailable(context: Context): Boolean { 95 | val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 96 | return intent.resolveActivity(context.packageManager) != null 97 | } 98 | 99 | /** 100 | * Get Intent to View Uri backed File 101 | * 102 | * @param context 103 | * @param uri 104 | * @return Intent 105 | */ 106 | @JvmStatic 107 | fun getUriViewIntent(context: Context, uri: Uri): Intent { 108 | val intent = Intent(Intent.ACTION_VIEW) 109 | val authority = 110 | context.packageName + context.getString(R.string.image_picker_provider_authority_suffix) 111 | 112 | val file = DocumentFile.fromSingleUri(context, uri) 113 | val dataUri = if (file?.canRead() == true) { 114 | uri 115 | } else { 116 | val filePath = FileUriUtils.getRealPath(context, uri)!! 117 | FileProvider.getUriForFile(context, authority, File(filePath)) 118 | } 119 | 120 | intent.setDataAndType(dataUri, "image/*") 121 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 122 | 123 | return intent 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /imagepicker/src/main/kotlin/com/github/dhaval2404/imagepicker/util/PermissionUtil.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.util 2 | 3 | import android.content.Context 4 | import android.content.pm.PackageManager 5 | import androidx.core.content.ContextCompat 6 | 7 | /** 8 | * Permission utility class 9 | * 10 | * @author Dhaval Patel 11 | * @version 1.0 12 | * @since 04 January 2019 13 | */ 14 | object PermissionUtil { 15 | 16 | /** 17 | * Check if Permission is granted 18 | * 19 | * @return true if specified permission is granted 20 | */ 21 | fun isPermissionGranted(context: Context, permission: String): Boolean { 22 | val selfPermission = ContextCompat.checkSelfPermission(context, permission) 23 | return selfPermission == PackageManager.PERMISSION_GRANTED 24 | } 25 | 26 | /** 27 | * Check if Specified Permissions are granted or not. If single permission is denied then 28 | * function will return false. 29 | * 30 | * @param context Application Context 31 | * @param permissions Array of Permission to Check 32 | * 33 | * @return true if all specified permission is granted 34 | */ 35 | fun isPermissionGranted(context: Context, permissions: Array): Boolean { 36 | return permissions.filter { 37 | isPermissionGranted(context, it) 38 | }.size == permissions.size 39 | } 40 | 41 | /** 42 | * Check if Specified Permission is defined in AndroidManifest.xml file or not. 43 | * If permission is defined in manifest then return true else return false. 44 | * 45 | * @param context Application Context 46 | * @param permission String Permission Name 47 | * 48 | * @return true if permission defined in AndroidManifest.xml file, else return false. 49 | */ 50 | fun isPermissionInManifest(context: Context, permission: String): Boolean { 51 | val packageInfo = context.packageManager.getPackageInfo( 52 | context.packageName, 53 | PackageManager.GET_PERMISSIONS 54 | ) 55 | val permissions = packageInfo.requestedPermissions 56 | 57 | if (permissions.isNullOrEmpty()) 58 | return false 59 | 60 | for (perm in permissions) { 61 | if (perm == permission) 62 | return true 63 | } 64 | 65 | return false 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-hdpi/ic_photo_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-hdpi/ic_photo_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-hdpi/ic_photo_camera_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-hdpi/ic_photo_camera_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-mdpi/ic_photo_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-mdpi/ic_photo_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-mdpi/ic_photo_camera_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-mdpi/ic_photo_camera_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xhdpi/ic_photo_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xhdpi/ic_photo_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xhdpi/ic_photo_camera_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xhdpi/ic_photo_camera_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xxhdpi/ic_photo_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xxhdpi/ic_photo_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xxhdpi/ic_photo_camera_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xxhdpi/ic_photo_camera_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xxxhdpi/ic_photo_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xxxhdpi/ic_photo_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/drawable-xxxhdpi/ic_photo_camera_black_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/imagepicker/src/main/res/drawable-xxxhdpi/ic_photo_camera_black_48dp.png -------------------------------------------------------------------------------- /imagepicker/src/main/res/layout/dialog_choose_app.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 18 | 19 | 24 | 25 | 32 | 33 | 34 | 35 | 43 | 44 | 49 | 50 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-ar/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | إختيار 6 | إلغاء 7 | معرض الصور 8 | كاميرا 9 | 10 | 11 | الترخيص.]]> 12 | 13 | تعذر إنشاء ملف الصورة الملتقطة بالكاميرا 14 | تعذر اختيار صورة من معرض الصور 15 | تعذر اقتصاص الصورة 16 | تعذر ضغط الصورة 17 | تم إلغاء المهمة 18 | لم يتم العثور على تطبيق الكاميرا 19 | 20 | 21 | 22 | أصلي 23 | تعديل الصورة 24 | اقتصاص 25 | تدوير 26 | تغيير الحجم 27 | اقتصاص 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-de/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Auswählen 3 | Abbrechen 4 | Galerie 5 | Kamera 6 | 7 | 8 | Berechtigungen.]]> 9 | 10 | Es konnte kein Foto aufgenommen werden 11 | Es konnte kein Foto aus der Galerie ausgewählt werden 12 | Foto konnte nicht zugeschnitten werden 13 | Foto konnte nicht komprimiert werden 14 | Vorgang abgebrochen 15 | Es wurde keine Kamera-App gefunden 16 | 17 | 18 | Original 19 | Foto bearbeiten 20 | Zuschneiden 21 | Drehen 22 | Skalieren 23 | Zuschneiden 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-es/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Elegir 6 | Cancelar 7 | Galeria 8 | Cámara 9 | 10 | 11 | Permisos.]]> 12 | 13 | Error al crear archivo de imagen de la Cámara 14 | Error al elegir imagen de la galería 15 | Error al recortar la imagen 16 | Error al comprimir la imagen 17 | Tarea cancelada 18 | No se encontró la aplicación de la cámara 19 | 20 | 21 | 22 | Original 23 | Editar Foto 24 | 25 | Cortar 26 | Rotar 27 | Escalar 28 | Cortar 29 | 30 | 31 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-fa/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | انتخاب 5 | لغو 6 | گالری 7 | دوربین 8 | 9 | 10 | 11 | 12 | خطا در ایجاد فایل تصویر گرفته شده از دوربین 13 | خطا در انتخاب عکس از گالری 14 | خطا در برش عکس 15 | خطا در فشرده سازی عکس 16 | عملیات لغو شد 17 | برنامه دوربین پیدا نشد 18 | 19 | 20 | 21 | اصلی 22 | ویرایش عکس 23 | برش 24 | چرخش 25 | مقیاس 26 | برش 27 | 28 | 29 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-fr/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Image Picker 3 | .imagepicker.provider 4 | 5 | Choisir 6 | Annuler 7 | Galerie 8 | Caméra 9 | 10 | 11 | Permissions.]]> 12 | 13 | Échec de la création du fichier image à partir de la caméra 14 | Échec de la sélection de l\'image dans la galerie 15 | Échec du recadrage de l\'image 16 | Échec à la compression de l\'image 17 | Tâche annulée 18 | L\'application de caméra n\'a pas été trouvée 19 | 20 | 21 | Original 22 | Édition de la photo 23 | Recadrage 24 | Pivoter 25 | Redimensionner 26 | Recadrer 27 | 28 | 29 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-gu/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | પસંદ કરો 6 | રદ કરો 7 | ગેલેરી 8 | કૅમેરા 9 | 10 | 11 | પરવાનગીથી સ્ટોરેજ પરવાનગીની મંજૂરી આપો.]]> 12 | 13 | કૅમેરા છબી ફાઇલ બનાવવામાં નિષ્ફળ 14 | ગેલેરી છબી પસંદ કરવામાં નિષ્ફળ 15 | છબી કાપવામાં નિષ્ફળ 16 | છબીને સંકુચિત કરવામાં નિષ્ફળ 17 | કાર્ય રદ કરવામાં આવ્યું છે 18 | કૅમેરા એપ્લિકેશન મળી નથી 19 | 20 | 21 | 22 | અસલ 23 | ફોટો સંપાદિત કરો 24 | કાપો 25 | ફેરવો 26 | સ્કેલ 27 | કાપો 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-hi/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | चुनें 6 | रद्द करें 7 | गेलरी 8 | कैमरा 9 | 10 | 11 | अनुमतियों से भंडारण की अनुमति दें।]]> 12 | 13 | कैमरा चित्र बनाने में विफल 14 | गैलरी की तस्वीर लेने में विफल 15 | चित्र को काटना में विफल 16 | छवि को संपीड़ित करने में विफल 17 | कार्य रद्द कर दिया गया 18 | कैमरा ऐप नहीं मिला 19 | 20 | 21 | 22 | मूल 23 | फ़ोटो संपादित करें 24 | काटना 25 | घुमाएँ 26 | स्केल 27 | काटना 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-in/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Pilih 3 | Batal 4 | Galeri 5 | Kamera 6 | 7 | 8 | Perizinan.]]> 9 | 10 | Membuat file gambar dari kamera gagal 11 | Pemilihan gambar dari galeri gagal 12 | Gambar gagal dipotong 13 | Gambar gagal dikompres 14 | Task dibatalkan 15 | Kamera tidak ditemukan 16 | 17 | 18 | Asli 19 | Edit foto 20 | Potong 21 | Memutar 22 | Skala 23 | Potong 24 | 25 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-nb-rNO/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Velg 5 | Avbryt 6 | Galleri 7 | Kamera 8 | 9 | 10 | Tillatelser.]]> 11 | 12 | Oppretting av bilde feilet 13 | Valg av bilde fra galleri feilet 14 | Bildebeskjæring feilet 15 | Bildekomprimering feilet 16 | Oppgave kansellert 17 | Kamera-app ikke funnet 18 | 19 | 20 | 21 | Original 22 | Rediger bilde 23 | Beskjær bilde 24 | Roter 25 | Skaler 26 | Beskjær 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-pl/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Wybierz 6 | Anuluj 7 | Galeria 8 | Aparat 9 | 10 | 11 | Uprawnienia.]]> 12 | 13 | Podczas zapisywania zdjęcia wystąpił błąd 14 | Nie udało się uzyskać dostępu do zdjęcia w galerii 15 | Nie udało się zmienić rozmiarów obrazu 16 | Podczas kompresji obrazu wystąpił błąd 17 | Zadanie przerwane 18 | Nie znaleziono aplikacji aparatu 19 | 20 | 21 | 22 | Oryginał 23 | Edytuj zdjęcie 24 | Przytnij 25 | Obróć 26 | Skaluj 27 | Przytnij 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-pt-rBR/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Escolher 6 | Cancelar 7 | Galeria 8 | Câmera 9 | 10 | 11 | Permissões.]]> 12 | 13 | App de câmera não encontrado 14 | Erro ao escolher imagem da galeria 15 | Erro ao compactar imagem 16 | Erro ao criar o arquivo da imagem da câmera 17 | Erro ao cortar imagem 18 | Tarefa cancelada 19 | 20 | 21 | 22 | Cortar 23 | Editar Foto 24 | Original 25 | Cortar 26 | Girar 27 | Tamanho 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-tr/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Image Picker 3 | .imagepicker.provider 4 | 5 | Seç 6 | Vazgeç 7 | Galeri 8 | Kamera 9 | 10 | 11 | İzinler\'den izin verin.]]> 12 | 13 | Kameradan fotoğraf çekilemedi 14 | Galeriden fotoğraf seçilemedi 15 | Fotoğraf kırpılamadı 16 | Fotoğraf sıkıştırılamadı 17 | Seçim iptal edildi 18 | Kamera uygulaması bulunamadı 19 | 20 | 21 | Orijinal 22 | Fotoğrafı Düzenle 23 | Kırp 24 | Döndür 25 | Ölçekle 26 | Kırp 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values-uz/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Tanlang 4 | Bekor qilish 5 | Galereya 6 | Kamera 7 | 8 | 9 | Ruhsatlar.]]> 10 | 11 | Kamera rasm fayli yaratishda xatolik yuz berdi 12 | Galereyadan rasm tanlashda xatolik yuz berdi 13 | Rasmni kesishda xatolik yuz berdi 14 | Rasmni zichlashda xatolik yuz berdi 15 | Vazifa bekor qilindi 16 | Kamera uchun dastur topilmadi 17 | 18 | 19 | 20 | Original 21 | Rasmni o\'zgartirish 22 | Kesish 23 | Aylantirish 24 | O\'lcham 25 | Kesish 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #757575 5 | #757575 6 | 7 | 8 | @color/ucrop_color_widget_active 9 | #787878 10 | @color/ucrop_color_widget_active 11 | @color/ucrop_color_widget_active 12 | @color/ucrop_color_widget_active 13 | #FFFFFF 14 | 15 | 16 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Image Picker 3 | .imagepicker.provider 4 | 5 | Choose 6 | Cancel 7 | Gallery 8 | Camera 9 | 10 | 11 | Permissions.]]> 12 | 13 | Failed to create Camera image file 14 | Failed to pick Gallery image 15 | Failed to crop image 16 | Failed to compress image 17 | Task Cancelled 18 | Camera app not found 19 | 20 | 21 | Original 22 | Edit Photo 23 | Crop 24 | Rotate 25 | Scale 26 | Crop 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /imagepicker/src/main/res/xml/image_picker_provider_paths.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 9 | 12 | -------------------------------------------------------------------------------- /imagepicker/src/test/java/com/github/dhaval2404/imagepicker/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import org.junit.Assert.assertEquals 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * @see [Testing documentation](http://d.android.com/tools/testing) 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | fun addition_isCorrect() { 14 | assertEquals(4, (2 + 2).toLong()) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ktlint.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | jcenter() 3 | } 4 | 5 | configurations { 6 | ktlint 7 | } 8 | 9 | dependencies { 10 | ktlint "com.pinterest:ktlint:0.41.0" 11 | // additional 3rd party ruleset(s) can be specified here 12 | // just add them to the classpath (e.g. ktlint 'groupId:artifactId:version') and 13 | // ktlint will pick them up 14 | } 15 | 16 | task ktlint(type: JavaExec, group: "verification") { 17 | description = "Check Kotlin code style." 18 | classpath = configurations.ktlint 19 | main = "com.pinterest.ktlint.Main" 20 | args "src/**/*.kt" 21 | // to generate report in checkstyle format prepend following args: 22 | // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml" 23 | // see https://github.com/pinterest/ktlint#usage for more 24 | } 25 | check.dependsOn ktlint 26 | 27 | task ktlintFormat(type: JavaExec, group: "formatting") { 28 | description = "Fix Kotlin code style deviations." 29 | classpath = configurations.ktlint 30 | main = "com.pinterest.ktlint.Main" 31 | args "-F", "src/**/*.kt" 32 | } -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | id 'kotlin-android-extensions' 5 | } 6 | 7 | apply from: "../ktlint.gradle" 8 | 9 | android { 10 | compileSdkVersion 30 11 | defaultConfig { 12 | applicationId "com.github.dhaval2404.imagepicker.sample" 13 | minSdkVersion 19 14 | targetSdkVersion 30 15 | versionCode 16 16 | versionName "2.1" 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | vectorDrawables.useSupportLibrary = true 19 | } 20 | buildTypes { 21 | release { 22 | minifyEnabled false 23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | sourceSets { 27 | main.java.srcDirs += 'src/main/kotlin' 28 | } 29 | compileOptions { 30 | sourceCompatibility JavaVersion.VERSION_1_8 31 | targetCompatibility JavaVersion.VERSION_1_8 32 | } 33 | } 34 | 35 | dependencies { 36 | implementation fileTree(dir: 'libs', include: ['*.jar']) 37 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 38 | 39 | implementation project(':imagepicker') 40 | 41 | implementation 'androidx.core:core-ktx:1.3.2' 42 | implementation 'androidx.appcompat:appcompat:1.2.0' 43 | implementation 'androidx.browser:browser:1.3.0' 44 | implementation 'com.google.android.material:material:1.3.0' 45 | implementation 'androidx.documentfile:documentfile:1.0.1' 46 | 47 | implementation "androidx.activity:activity-ktx:1.2.3" 48 | implementation "androidx.fragment:fragment-ktx:1.3.3" 49 | 50 | //Image Loading Lib 51 | implementation 'com.github.bumptech.glide:glide:4.11.0' 52 | 53 | //Leakcanary 54 | //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7' 55 | 56 | testImplementation 'junit:junit:4.13.2' 57 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 58 | androidTestImplementation 'androidx.test:core:1.3.0' 59 | 60 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 61 | androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' 62 | androidTestImplementation 'androidx.test:rules:1.3.0' 63 | androidTestImplementation 'androidx.test:runner:1.3.0' 64 | } 65 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/github/dhaval2404/imagepicker/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import androidx.test.ext.junit.runners.AndroidJUnit4 4 | import androidx.test.platform.app.InstrumentationRegistry 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | /** 10 | * Instrumented test, which will execute on an Android device. 11 | * 12 | * See [testing documentation](http://d.android.com/tools/testing). 13 | */ 14 | @RunWith(AndroidJUnit4::class) 15 | class ExampleInstrumentedTest { 16 | @Test 17 | fun useAppContext() { 18 | // Context of the app under test. 19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 20 | assertEquals("com.github.dhaval2404.imageprovider", appContext.packageName) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/github/dhaval2404/imagepicker/MainActivityEspressoTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import androidx.test.espresso.Espresso.onView 4 | import androidx.test.espresso.action.ViewActions 5 | import androidx.test.espresso.assertion.ViewAssertions.matches 6 | import androidx.test.espresso.matcher.ViewMatchers.isDisplayed 7 | import androidx.test.espresso.matcher.ViewMatchers.withId 8 | import androidx.test.ext.junit.runners.AndroidJUnit4 9 | import androidx.test.rule.ActivityTestRule 10 | import com.github.dhaval2404.imagepicker.sample.MainActivity 11 | import com.github.dhaval2404.imagepicker.sample.R 12 | import org.junit.Rule 13 | import org.junit.Test 14 | import org.junit.runner.RunWith 15 | 16 | @RunWith(AndroidJUnit4::class) 17 | class MainActivityEspressoTest { 18 | 19 | @get:Rule 20 | var activityRule: ActivityTestRule = 21 | ActivityTestRule(MainActivity::class.java) 22 | 23 | @Test 24 | fun ensureButtonDisableAfterOneClick() { 25 | onView(withId(R.id.fab_add_photo)).check(matches(isDisplayed())) 26 | onView(withId(R.id.fab_add_gallery_photo)).check(matches(isDisplayed())) 27 | onView(withId(R.id.fab_add_camera_photo)).perform(ViewActions.scrollTo()).check(matches(isDisplayed())) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /sample/src/main/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/ic_launcher-web.png -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/ImageViewExtension.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample 2 | 3 | import android.net.Uri 4 | import android.widget.ImageView 5 | import androidx.annotation.DrawableRes 6 | import com.bumptech.glide.Glide 7 | import com.bumptech.glide.request.RequestOptions 8 | 9 | fun ImageView.setDrawableImage(@DrawableRes resource: Int, applyCircle: Boolean = false) { 10 | val glide = Glide.with(this).load(resource) 11 | if (applyCircle) { 12 | glide.apply(RequestOptions.circleCropTransform()).into(this) 13 | } else { 14 | glide.into(this) 15 | } 16 | } 17 | 18 | fun ImageView.setLocalImage(uri: Uri, applyCircle: Boolean = false) { 19 | val glide = Glide.with(this).load(uri) 20 | if (applyCircle) { 21 | glide.apply(RequestOptions.circleCropTransform()).into(this) 22 | } else { 23 | glide.into(this) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/ImageViewerDialog.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import androidx.fragment.app.DialogFragment 8 | import kotlinx.android.synthetic.main.dialog_imageviewer.* 9 | 10 | /** 11 | * Dialog to View Image 12 | * 13 | * @author Dhaval Patel 14 | * @version 1.6 15 | * @since 05 January 2019 16 | */ 17 | class ImageViewerDialog : DialogFragment() { 18 | 19 | companion object { 20 | 21 | private const val EXTRA_IMAGE_RESOURCE = "extra.image_resource" 22 | 23 | @JvmStatic 24 | fun newInstance(resource: Int) = ImageViewerDialog().apply { 25 | arguments = Bundle().apply { 26 | putInt(EXTRA_IMAGE_RESOURCE, resource) 27 | } 28 | } 29 | } 30 | 31 | override fun onCreateView( 32 | inflater: LayoutInflater, 33 | container: ViewGroup?, 34 | savedInstanceState: Bundle? 35 | ): View? { 36 | return inflater.inflate(R.layout.dialog_imageviewer, container, false) 37 | } 38 | 39 | override fun onActivityCreated(savedInstanceState: Bundle?) { 40 | super.onActivityCreated(savedInstanceState) 41 | codeImg.setImageResource(arguments?.getInt(EXTRA_IMAGE_RESOURCE, 0) ?: 0) 42 | } 43 | 44 | override fun onStart() { 45 | super.onStart() 46 | dialog?.window?.let { 47 | val width = ViewGroup.LayoutParams.MATCH_PARENT 48 | val height = ViewGroup.LayoutParams.WRAP_CONTENT 49 | it.setLayout(width, height) 50 | it.setBackgroundDrawableResource(android.R.color.transparent) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.net.Uri 6 | import android.os.Bundle 7 | import android.os.Environment 8 | import android.util.Log 9 | import android.view.Menu 10 | import android.view.MenuItem 11 | import android.view.View 12 | import android.widget.Toast 13 | import androidx.appcompat.app.AlertDialog 14 | import androidx.appcompat.app.AppCompatActivity 15 | import androidx.appcompat.app.AppCompatDelegate 16 | import com.github.dhaval2404.imagepicker.ImagePicker 17 | import com.github.dhaval2404.imagepicker.sample.util.FileUtil 18 | import com.github.dhaval2404.imagepicker.sample.util.IntentUtil 19 | import com.github.dhaval2404.imagepicker.util.IntentUtils 20 | import kotlinx.android.synthetic.main.activity_main.* 21 | import kotlinx.android.synthetic.main.content_camera_only.* 22 | import kotlinx.android.synthetic.main.content_gallery_only.* 23 | import kotlinx.android.synthetic.main.content_profile.* 24 | import java.io.File 25 | 26 | class MainActivity : AppCompatActivity() { 27 | 28 | companion object { 29 | 30 | private const val GITHUB_REPOSITORY = "https://github.com/Dhaval2404/ImagePicker" 31 | 32 | private const val PROFILE_IMAGE_REQ_CODE = 101 33 | private const val GALLERY_IMAGE_REQ_CODE = 102 34 | private const val CAMERA_IMAGE_REQ_CODE = 103 35 | } 36 | 37 | private var mCameraUri: Uri? = null 38 | private var mGalleryUri: Uri? = null 39 | private var mProfileUri: Uri? = null 40 | 41 | override fun onCreate(savedInstanceState: Bundle?) { 42 | AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) 43 | super.onCreate(savedInstanceState) 44 | setContentView(R.layout.activity_main) 45 | setSupportActionBar(toolbar) 46 | imgProfile.setDrawableImage(R.drawable.ic_person, true) 47 | } 48 | 49 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 50 | menuInflater.inflate(R.menu.menu_main, menu) 51 | return super.onCreateOptionsMenu(menu) 52 | } 53 | 54 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 55 | when (item.itemId) { 56 | R.id.action_github -> { 57 | IntentUtil.openURL(this, GITHUB_REPOSITORY) 58 | return true 59 | } 60 | } 61 | return super.onOptionsItemSelected(item) 62 | } 63 | 64 | /*private val startForProfileImageResult = 65 | registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> 66 | val resultCode = result.resultCode 67 | val data = result.data 68 | 69 | if (resultCode == Activity.RESULT_OK) { 70 | // Image Uri will not be null for RESULT_OK 71 | val fileUri = data?.data!! 72 | 73 | mProfileUri = fileUri 74 | imgProfile.setLocalImage(fileUri, true) 75 | } else if (resultCode == ImagePicker.RESULT_ERROR) { 76 | Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show() 77 | } else { 78 | Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show() 79 | } 80 | }*/ 81 | 82 | @Suppress("UNUSED_PARAMETER") 83 | fun pickProfileImage(view: View) { 84 | ImagePicker.with(this) 85 | // Crop Square image 86 | .galleryOnly() 87 | .cropSquare() 88 | .setImageProviderInterceptor { imageProvider -> // Intercept ImageProvider 89 | Log.d("ImagePicker", "Selected ImageProvider: " + imageProvider.name) 90 | } 91 | .setDismissListener { 92 | Log.d("ImagePicker", "Dialog Dismiss") 93 | } 94 | // Image resolution will be less than 512 x 512 95 | .maxResultSize(200, 200) 96 | .start(PROFILE_IMAGE_REQ_CODE) 97 | } 98 | 99 | @Suppress("UNUSED_PARAMETER") 100 | fun pickGalleryImage(view: View) { 101 | ImagePicker.with(this) 102 | // Crop Image(User can choose Aspect Ratio) 103 | .crop() 104 | // User can only select image from Gallery 105 | .galleryOnly() 106 | 107 | .galleryMimeTypes( // no gif images at all 108 | mimeTypes = arrayOf( 109 | "image/png", 110 | "image/jpg", 111 | "image/jpeg" 112 | ) 113 | ) 114 | // Image resolution will be less than 1080 x 1920 115 | .maxResultSize(1080, 1920) 116 | // .saveDir(getExternalFilesDir(null)!!) 117 | .start(GALLERY_IMAGE_REQ_CODE) 118 | } 119 | 120 | /** 121 | * Ref: https://gist.github.com/granoeste/5574148 122 | */ 123 | @Suppress("UNUSED_PARAMETER") 124 | fun pickCameraImage(view: View) { 125 | ImagePicker.with(this) 126 | // User can only capture image from Camera 127 | .cameraOnly() 128 | // Image size will be less than 1024 KB 129 | // .compress(1024) 130 | // Path: /storage/sdcard0/Android/data/package/files 131 | .saveDir(getExternalFilesDir(null)!!) 132 | // Path: /storage/sdcard0/Android/data/package/files/DCIM 133 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_DCIM)!!) 134 | // Path: /storage/sdcard0/Android/data/package/files/Download 135 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!) 136 | // Path: /storage/sdcard0/Android/data/package/files/Pictures 137 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!) 138 | // Path: /storage/sdcard0/Android/data/package/files/Pictures/ImagePicker 139 | .saveDir(File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!, "ImagePicker")) 140 | // Path: /storage/sdcard0/Android/data/package/files/ImagePicker 141 | .saveDir(getExternalFilesDir("ImagePicker")!!) 142 | // Path: /storage/sdcard0/Android/data/package/cache/ImagePicker 143 | .saveDir(File(getExternalCacheDir(), "ImagePicker")) 144 | // Path: /data/data/package/cache/ImagePicker 145 | .saveDir(File(getCacheDir(), "ImagePicker")) 146 | // Path: /data/data/package/files/ImagePicker 147 | .saveDir(File(getFilesDir(), "ImagePicker")) 148 | 149 | // Below saveDir path will not work, So do not use it 150 | // Path: /storage/sdcard0/DCIM 151 | // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)) 152 | // Path: /storage/sdcard0/Pictures 153 | // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)) 154 | // Path: /storage/sdcard0/ImagePicker 155 | // .saveDir(File(Environment.getExternalStorageDirectory(), "ImagePicker")) 156 | 157 | .start(CAMERA_IMAGE_REQ_CODE) 158 | } 159 | 160 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 161 | super.onActivityResult(requestCode, resultCode, data) 162 | if (resultCode == Activity.RESULT_OK) { 163 | // Uri object will not be null for RESULT_OK 164 | val uri: Uri = data?.data!! 165 | when (requestCode) { 166 | PROFILE_IMAGE_REQ_CODE -> { 167 | mProfileUri = uri 168 | imgProfile.setLocalImage(uri, true) 169 | } 170 | GALLERY_IMAGE_REQ_CODE -> { 171 | mGalleryUri = uri 172 | imgGallery.setLocalImage(uri) 173 | } 174 | CAMERA_IMAGE_REQ_CODE -> { 175 | mCameraUri = uri 176 | imgCamera.setLocalImage(uri) 177 | } 178 | } 179 | } else if (resultCode == ImagePicker.RESULT_ERROR) { 180 | Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show() 181 | } else { 182 | Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show() 183 | } 184 | } 185 | 186 | fun showImageCode(view: View) { 187 | val resource = when (view) { 188 | imgProfileCode -> R.drawable.img_profile_code 189 | imgCameraCode -> R.drawable.img_camera_code 190 | imgGalleryCode -> R.drawable.img_gallery_code 191 | else -> 0 192 | } 193 | ImageViewerDialog.newInstance(resource).show(supportFragmentManager, "") 194 | } 195 | 196 | fun showImage(view: View) { 197 | val uri = when (view) { 198 | imgProfile -> mProfileUri 199 | imgCamera -> mCameraUri 200 | imgGallery -> mGalleryUri 201 | else -> null 202 | } 203 | 204 | uri?.let { 205 | startActivity(IntentUtils.getUriViewIntent(this, uri)) 206 | } 207 | } 208 | 209 | fun showImageInfo(view: View) { 210 | val uri = when (view) { 211 | imgProfileInfo -> mProfileUri 212 | imgCameraInfo -> mCameraUri 213 | imgGalleryInfo -> mGalleryUri 214 | else -> null 215 | } 216 | 217 | AlertDialog.Builder(this) 218 | .setTitle("Image Info") 219 | .setMessage(FileUtil.getFileInfo(this, uri)) 220 | .setPositiveButton("Ok", null) 221 | .show() 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/SampleActivity.java: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.os.Environment; 9 | import android.util.Log; 10 | import android.view.Menu; 11 | import android.view.MenuItem; 12 | import android.view.View; 13 | import android.widget.ImageView; 14 | import android.widget.Toast; 15 | 16 | import androidx.annotation.NonNull; 17 | import androidx.annotation.Nullable; 18 | import androidx.appcompat.app.AppCompatActivity; 19 | import androidx.appcompat.app.AppCompatDelegate; 20 | import androidx.appcompat.widget.Toolbar; 21 | 22 | import com.github.dhaval2404.imagepicker.ImagePicker; 23 | import com.github.dhaval2404.imagepicker.constant.ImageProvider; 24 | import com.github.dhaval2404.imagepicker.listener.DismissListener; 25 | import com.github.dhaval2404.imagepicker.sample.util.FileUtil; 26 | import com.github.dhaval2404.imagepicker.sample.util.IntentUtil; 27 | import com.github.dhaval2404.imagepicker.util.IntentUtils; 28 | 29 | import java.io.File; 30 | 31 | import kotlin.Unit; 32 | import kotlin.jvm.functions.Function1; 33 | 34 | public class SampleActivity extends AppCompatActivity { 35 | 36 | private static final String GITHUB_REPOSITORY = "https://github.com/Dhaval2404/ImagePicker"; 37 | 38 | private static final int PROFILE_IMAGE_REQ_CODE = 101; 39 | private static final int GALLERY_IMAGE_REQ_CODE = 102; 40 | private static final int CAMERA_IMAGE_REQ_CODE = 103; 41 | 42 | private Uri mCameraUri; 43 | private Uri mGalleryUri; 44 | private Uri mProfileUri; 45 | 46 | private ImageView imgProfileInfo; 47 | private ImageView imgCameraInfo; 48 | private ImageView imgGalleryInfo; 49 | 50 | private ImageView imgProfile; 51 | private ImageView imgGallery; 52 | private ImageView imgCamera; 53 | 54 | private ImageView imgProfileCode; 55 | private ImageView imgGalleryCode; 56 | private ImageView imgCameraCode; 57 | 58 | @Override 59 | protected void onCreate(@Nullable Bundle savedInstanceState) { 60 | AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); 61 | super.onCreate(savedInstanceState); 62 | setContentView(R.layout.activity_main); 63 | 64 | 65 | Toolbar toolbar = findViewById(R.id.toolbar); 66 | setSupportActionBar(toolbar); 67 | 68 | imgProfileInfo = findViewById(R.id.imgProfileInfo); 69 | imgCameraInfo = findViewById(R.id.imgCameraInfo); 70 | imgGalleryInfo = findViewById(R.id.imgGalleryInfo); 71 | 72 | imgProfile = findViewById(R.id.imgProfile); 73 | imgCamera = findViewById(R.id.imgCamera); 74 | imgGallery = findViewById(R.id.imgGallery); 75 | 76 | imgProfileCode = findViewById(R.id.imgProfileCode); 77 | imgCameraCode = findViewById(R.id.imgCameraCode); 78 | imgGalleryCode = findViewById(R.id.imgGalleryCode); 79 | 80 | ImageViewExtensionKt.setDrawableImage(imgProfile, R.drawable.ic_person, true); 81 | } 82 | 83 | @Override 84 | public boolean onCreateOptionsMenu(Menu menu) { 85 | getMenuInflater().inflate(R.menu.menu_main, menu); 86 | return super.onCreateOptionsMenu(menu); 87 | } 88 | 89 | @Override 90 | public boolean onOptionsItemSelected(@NonNull MenuItem item) { 91 | if (item.getItemId() == R.id.action_github) { 92 | IntentUtil.openURL(this, GITHUB_REPOSITORY); 93 | return true; 94 | } 95 | return super.onOptionsItemSelected(item); 96 | } 97 | 98 | public void pickProfileImage(View view) { 99 | ImagePicker.with(this) 100 | // Crop Square image 101 | .cropSquare() 102 | .setImageProviderInterceptor(new Function1() { 103 | @Override 104 | public Unit invoke(ImageProvider imageProvider) { 105 | Log.d("ImagePicker", "Selected ImageProvider: " + imageProvider.toString()); 106 | return null; 107 | } 108 | }).setDismissListener(new DismissListener() { 109 | @Override 110 | public void onDismiss() { 111 | Log.d("ImagePicker", "Dialog Dismiss"); 112 | } 113 | }) 114 | // Image resolution will be less than 512 x 512 115 | .maxResultSize(200, 200) 116 | .start(PROFILE_IMAGE_REQ_CODE); 117 | } 118 | 119 | public void pickGalleryImage(View view) { 120 | ImagePicker.with(this) 121 | // Crop Image(User can choose Aspect Ratio) 122 | .crop() 123 | // User can only select image from Gallery 124 | .galleryOnly() 125 | 126 | .galleryMimeTypes(new String[]{"image/png", 127 | "image/jpg", 128 | "image/jpeg" 129 | }) 130 | // Image resolution will be less than 1080 x 1920 131 | .maxResultSize(1080, 1920) 132 | // .saveDir(getExternalFilesDir(null)) 133 | .start(GALLERY_IMAGE_REQ_CODE); 134 | } 135 | 136 | /** 137 | * Ref: https://gist.github.com/granoeste/5574148 138 | */ 139 | public void pickCameraImage(View view) { 140 | ImagePicker.with(this) 141 | // User can only capture image from Camera 142 | .cameraOnly() 143 | // Image size will be less than 1024 KB 144 | // .compress(1024) 145 | // Path: /storage/sdcard0/Android/data/package/files 146 | .saveDir(getExternalFilesDir(null)) 147 | // Path: /storage/sdcard0/Android/data/package/files/DCIM 148 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_DCIM)) 149 | // Path: /storage/sdcard0/Android/data/package/files/Download 150 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)) 151 | // Path: /storage/sdcard0/Android/data/package/files/Pictures 152 | .saveDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES)) 153 | // Path: /storage/sdcard0/Android/data/package/files/Pictures/ImagePicker 154 | .saveDir(new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ImagePicker")) 155 | // Path: /storage/sdcard0/Android/data/package/files/ImagePicker 156 | .saveDir(getExternalFilesDir("ImagePicker")) 157 | // Path: /storage/sdcard0/Android/data/package/cache/ImagePicker 158 | .saveDir(new File(getExternalCacheDir(), "ImagePicker")) 159 | // Path: /data/data/package/cache/ImagePicker 160 | .saveDir(new File(getCacheDir(), "ImagePicker")) 161 | // Path: /data/data/package/files/ImagePicker 162 | .saveDir(new File(getFilesDir(), "ImagePicker")) 163 | 164 | // Below saveDir path will not work, So do not use it 165 | // Path: /storage/sdcard0/DCIM 166 | // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)) 167 | // Path: /storage/sdcard0/Pictures 168 | // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)) 169 | // Path: /storage/sdcard0/ImagePicker 170 | // .saveDir(File(Environment.getExternalStorageDirectory(), "ImagePicker")) 171 | 172 | .start(CAMERA_IMAGE_REQ_CODE); 173 | } 174 | 175 | public void showImageCode(View view) { 176 | int resource = 0; 177 | if (view == imgProfileCode) { 178 | resource = R.drawable.img_profile_code; 179 | } else if (view == imgCameraCode) { 180 | resource = R.drawable.img_camera_code; 181 | } else if (view == imgGalleryCode) { 182 | resource = R.drawable.img_gallery_code; 183 | } 184 | ImageViewerDialog 185 | .newInstance(resource) 186 | .show(getSupportFragmentManager(), ""); 187 | } 188 | 189 | public void showImage(View view) { 190 | Uri uri; 191 | if (view == imgProfile) { 192 | uri = mProfileUri; 193 | } else if (view == imgCamera) { 194 | uri = mCameraUri; 195 | } else if (view == imgGallery) { 196 | uri = mGalleryUri; 197 | } else { 198 | uri = null; 199 | } 200 | 201 | if (uri != null) { 202 | startActivity(IntentUtils.getUriViewIntent(this, uri)); 203 | } 204 | } 205 | 206 | public void showImageInfo(View view) { 207 | Uri uri; 208 | if (view == imgProfileInfo) { 209 | uri = mProfileUri; 210 | } else if (view == imgCameraInfo) { 211 | uri = mCameraUri; 212 | } else if (view == imgGalleryInfo) { 213 | uri = mGalleryUri; 214 | } else { 215 | uri = null; 216 | } 217 | 218 | new AlertDialog.Builder(this) 219 | .setTitle("Image Info") 220 | .setMessage(FileUtil.getFileInfo(this, uri)) 221 | .setPositiveButton("Ok", null) 222 | .show(); 223 | } 224 | 225 | @Override 226 | protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { 227 | super.onActivityResult(requestCode, resultCode, data); 228 | if (resultCode == Activity.RESULT_OK) { 229 | // Uri object will not be null for RESULT_OK 230 | Uri uri = data.getData(); 231 | 232 | switch (requestCode) { 233 | case PROFILE_IMAGE_REQ_CODE: 234 | mProfileUri = uri; 235 | ImageViewExtensionKt.setLocalImage(imgProfile, uri, true); 236 | break; 237 | case GALLERY_IMAGE_REQ_CODE: 238 | mGalleryUri = uri; 239 | ImageViewExtensionKt.setLocalImage(imgGallery, uri, false); 240 | break; 241 | case CAMERA_IMAGE_REQ_CODE: 242 | mCameraUri = uri; 243 | ImageViewExtensionKt.setLocalImage(imgCamera, uri, false); 244 | break; 245 | } 246 | } else if (resultCode == ImagePicker.RESULT_ERROR) { 247 | Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show(); 248 | } else { 249 | Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show(); 250 | } 251 | } 252 | 253 | } -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/util/FileUtil.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample.util 2 | 3 | import android.content.Context 4 | import android.net.Uri 5 | import android.util.Log 6 | import com.github.dhaval2404.imagepicker.util.FileUriUtils 7 | import com.github.dhaval2404.imagepicker.util.FileUtil 8 | import java.io.File 9 | import java.text.SimpleDateFormat 10 | import java.util.Locale 11 | 12 | /** 13 | * File Utility 14 | * 15 | * @author Dhaval Patel 16 | * @version 1.6 17 | * @since 05 January 2019 18 | */ 19 | object FileUtil { 20 | 21 | /** 22 | * @param context Context 23 | * @param uri Uri 24 | * @return Image Info 25 | */ 26 | @JvmStatic 27 | fun getFileInfo(context: Context, uri: Uri?): String { 28 | if (uri == null) { 29 | return "Image not found" 30 | } 31 | 32 | // Get Resolution 33 | val resolution = FileUtil.getImageResolution(context, uri) 34 | 35 | // File Path 36 | val filePath = FileUriUtils.getRealPath(context, uri) 37 | val document = FileUtil.getDocumentFile(context, uri) ?: return "Image not found" 38 | 39 | // Get Last Modified 40 | val sdf = SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.getDefault()) 41 | val modified = sdf.format(document.lastModified()) 42 | 43 | // File Size 44 | val fileSize = getFileSize(document.length()) 45 | 46 | return StringBuilder() 47 | 48 | .append("Resolution: ") 49 | .append("${resolution.first}x${resolution.second}") 50 | .append("\n\n") 51 | 52 | .append("Modified: ") 53 | .append(modified) 54 | .append("\n\n") 55 | 56 | .append("File Size: ") 57 | .append(fileSize) 58 | .append("\n\n") 59 | 60 | /*.append("File Name: ") 61 | .append(getFileName(context.contentResolver, uri)) 62 | .append("\n\n")*/ 63 | 64 | .append("File Path: ") 65 | .append(filePath) 66 | .append("\n\n") 67 | 68 | .append("Uri Path: ") 69 | .append(uri.toString()) 70 | .toString() 71 | } 72 | 73 | private fun getFileSize(fileSize: Long): String { 74 | val mb = fileSize / (1024 * 1024) 75 | val kb = fileSize / (1024) 76 | 77 | return if (mb > 1) { 78 | "$mb MB" 79 | } else { 80 | "$kb KB" 81 | } 82 | } 83 | 84 | /*private fun getFileName(contentResolver: ContentResolver, uri: Uri): String? { 85 | if (ContentResolver.SCHEME_FILE == uri.scheme) { 86 | return File(uri.path).getName() 87 | } else if (ContentResolver.SCHEME_CONTENT == uri.scheme) { 88 | return getCursorContent(contentResolver, uri) 89 | } 90 | return null 91 | } 92 | 93 | private fun getCursorContent( 94 | contentResolver: ContentResolver, 95 | uri: Uri 96 | ): String? { 97 | return try { 98 | val cursor = contentResolver.query(uri, null, null, null, null) ?: return null 99 | var fileName: String? = null 100 | if (cursor.moveToFirst()) { 101 | fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) 102 | } 103 | cursor.close() 104 | fileName 105 | } catch (ex: Exception) { 106 | null 107 | } 108 | }*/ 109 | 110 | fun printFileInfo(file: File?) { 111 | if (file == null) { 112 | Log.i("File Info", "File object is null") 113 | return 114 | } 115 | 116 | // Get Resolution 117 | val resolution = FileUtil.getImageResolution(file) 118 | 119 | val info = StringBuilder() 120 | .append("Resolution: ") 121 | .append("${resolution.first}x${resolution.second}") 122 | .append("\n") 123 | 124 | .append("File Size: ") 125 | .append(getFileSize(file.length())) 126 | .append("\n") 127 | 128 | .append("File Name: ") 129 | .append(file.name) 130 | .append("\n") 131 | 132 | .append("File Path: ") 133 | .append(file.absoluteFile) 134 | .toString() 135 | Log.i("File Info", info) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /sample/src/main/kotlin/com.github.dhaval2404.imagepicker/sample/util/IntentUtil.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker.sample.util 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.net.Uri 6 | import androidx.browser.customtabs.CustomTabsIntent 7 | import androidx.core.content.FileProvider 8 | import com.github.dhaval2404.imagepicker.R 9 | import java.io.File 10 | 11 | /** 12 | * Intent Utility 13 | * 14 | * @author Dhaval Patel 15 | * @version 1.6 16 | * @since 05 January 2019 17 | */ 18 | object IntentUtil { 19 | 20 | /** 21 | * View Image in 3rd party apps 22 | * 23 | * @param activity Activity Instance 24 | * @param file Image File 25 | * 26 | */ 27 | fun showImage(activity: Activity, file: File) { 28 | val intent = Intent(Intent.ACTION_VIEW) 29 | val authority = activity.packageName + activity.getString(R.string.image_picker_provider_authority_suffix) 30 | val uri = FileProvider.getUriForFile(activity, authority, file) 31 | intent.setDataAndType(uri, "image/*") 32 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 33 | activity.startActivity(intent) 34 | } 35 | 36 | /** 37 | * Open URL using chrome custom Tabs 38 | * 39 | * @param activity Activity Instance 40 | * @param url Valid http/https URL 41 | * 42 | */ 43 | @JvmStatic 44 | fun openURL(activity: Activity, url: String) { 45 | val link = Uri.parse(url) 46 | CustomTabsIntent.Builder() 47 | .build() 48 | .launchUrl(activity, link) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/ic_github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/drawable-hdpi/ic_github.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/baseline_photo_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/baseline_photo_camera_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 13 | 14 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_person.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/img_camera_code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/drawable/img_camera_code.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/img_gallery_code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/drawable/img_gallery_code.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/img_profile_code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/drawable/img_profile_code.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/outline_cloud_upload_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/outline_code_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/outline_info_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/profile_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/content_camera_only.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 17 | 18 | 24 | 25 | 31 | 32 | 37 | 38 | 46 | 47 | 48 | 49 | 54 | 55 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/content_gallery_only.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 17 | 18 | 24 | 25 | 31 | 32 | 37 | 38 | 46 | 47 | 48 | 49 | 54 | 55 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/content_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 15 | 16 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/content_profile.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | 26 | 27 | 33 | 34 | 35 | 36 | 44 | 45 | 54 | 55 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/dialog_imageviewer.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-hdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-mdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dhaval2404/ImagePicker/1ef2d9cd4bdf6cc3f851a8ee987bf828b164a045/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | @color/teal_500 4 | @color/teal_300 5 | @color/teal_700 6 | @color/orange_500 7 | 8 | @color/teal_500 9 | @color/teal_700 10 | @color/teal_500 11 | #fff 12 | 13 | @color/grey_600 14 | @color/grey_600 15 | 16 | 17 | -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 16dp 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFFFFF 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Image Picker 3 | Github Repository 4 | 5 | Camera Only 6 | Gallery Only 7 | 8 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 14 | 26 | 27 | 33 | 34 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /sample/src/test/java/com/github/dhaval2404/imagepicker/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.dhaval2404.imagepicker 2 | 3 | import org.junit.Assert.assertEquals 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * See [testing documentation](http://d.android.com/tools/testing). 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | fun addition_isCorrect() { 14 | assertEquals(4, 2 + 2) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sample', ':imagepicker' 2 | --------------------------------------------------------------------------------