├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── in
│ │ └── mayanknagwanshi
│ │ └── imagepicker
│ │ └── demo
│ │ ├── ExampleActivity.java
│ │ └── MainActivity.java
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ ├── activity_example.xml
│ ├── activity_example_fragment.xml
│ ├── activity_main.xml
│ └── fragment_example.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── imagepicker
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── in
│ │ └── mayanknagwanshi
│ │ └── imagepicker
│ │ ├── ImageCropActivity.java
│ │ ├── ImageSelectActivity.java
│ │ ├── imageCompression
│ │ ├── ImageCompression.java
│ │ └── ImageCompressionListener.java
│ │ ├── imagePicker
│ │ └── ImagePickerUtil.java
│ │ ├── provider
│ │ └── ImageSelectionProvider.java
│ │ └── view
│ │ └── ImageCropView.java
│ └── res
│ ├── drawable-nodpi
│ └── frame.png
│ ├── layout
│ ├── activity_image_crop.xml
│ └── activity_image_select.xml
│ ├── values
│ └── strings.xml
│ └── xml
│ └── provider_paths.xml
├── jitpack.yml
├── sample.gif
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | .DS_Store
9 | /build
10 | /captures
11 | .externalNativeBuild
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Mayank Nagwanshi
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ImagePicker 
2 | Android library to choose image from gallery or camera with option to compress result image.
3 |
4 | # Download [](https://jitpack.io/#maayyaannkk/ImagePicker) []( https://android-arsenal.com/details/1/7055 )
5 |
6 | Add this to your project's `build.gradle`
7 |
8 | ```groovy
9 | allprojects {
10 | repositories {
11 | maven { url "https://jitpack.io" }
12 | }
13 | }
14 | ```
15 |
16 | And add this to your module's `build.gradle`
17 |
18 | ```groovy
19 | dependencies {
20 | implementation 'com.github.maayyaannkk:ImagePicker:x.y.z'
21 | }
22 | ```
23 |
24 | change `x.y.z` to version in [](https://jitpack.io/#maayyaannkk/ImagePicker)
25 |
26 | ## Usage
27 |
28 | For full example, please refer to `app` module
29 |
30 | No need to request for write external storage permission, library will do that.
31 | ### Crop with 1:1 aspect ratio
32 |
33 |
34 | ### Start image picker activity
35 |
36 | The simplest way to start is setup options and start the activity. Set the FLAG_CROP to crop resulting image in 1:1 aspect ratio
37 | ```java
38 | Intent intent = new Intent(this, ImageSelectActivity.class);
39 | intent.putExtra(ImageSelectActivity.FLAG_COMPRESS, false);//default is true
40 | intent.putExtra(ImageSelectActivity.FLAG_CAMERA, true);//default is true
41 | intent.putExtra(ImageSelectActivity.FLAG_GALLERY, true);//default is true
42 | intent.putExtra(ImageSelectActivity.FLAG_CROP, isCrop);//default is false
43 | startActivityForResult(intent, 1213);
44 | ```
45 | Receive result
46 | ```java
47 | @Override
48 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
49 | super.onActivityResult(requestCode, resultCode, data);
50 | if (requestCode == 1213 && resultCode == Activity.RESULT_OK) {
51 | String filePath = data.getStringExtra(ImageSelectActivity.RESULT_FILE_PATH);
52 | Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
53 | imageView.setImageBitmap(selectedImage);
54 | }
55 | }
56 | ```
57 | ## Corner cases
58 | throws IllegalStateException if:
59 | -chooseFromCamera and chooseFromGallery both are false
60 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdk 33
5 | buildFeatures.buildConfig true
6 | namespace "in.mayanknagwanshi.imagepicker.demo"
7 | defaultConfig {
8 | applicationId "in.mayanknagwanshi.imagepicker.demo"
9 | minSdkVersion 19
10 | targetSdkVersion 32
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | implementation project(':imagepicker')
25 | implementation 'androidx.appcompat:appcompat:1.3.0'
26 | //testImplementation 'junit:junit:4.12'
27 | //androidTestImplementation 'com.android.support.test:runner:1.0.1'
28 | //androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
29 | }
30 |
--------------------------------------------------------------------------------
/app/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 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/in/mayanknagwanshi/imagepicker/demo/ExampleActivity.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.demo;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.os.Bundle;
8 | import android.widget.ImageView;
9 |
10 | import androidx.appcompat.app.AppCompatActivity;
11 |
12 | import in.mayanknagwanshi.imagepicker.ImageSelectActivity;
13 |
14 | public class ExampleActivity extends AppCompatActivity {
15 | private ImageView imageView;
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_example);
21 |
22 | imageView = findViewById(R.id.imageView);
23 | ImageSelectActivity.startImageSelectionForResult(this, true, true, true, true, 1213);
24 | }
25 |
26 | @Override
27 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
28 | super.onActivityResult(requestCode, resultCode, data);
29 | if (requestCode == 1213 && resultCode == Activity.RESULT_OK) {
30 | String filePath = data.getStringExtra(ImageSelectActivity.RESULT_FILE_PATH);
31 | Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
32 | imageView.setImageBitmap(selectedImage);
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/java/in/mayanknagwanshi/imagepicker/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.demo;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.view.View;
6 | import android.widget.Button;
7 |
8 | import androidx.appcompat.app.AppCompatActivity;
9 |
10 | public class MainActivity extends AppCompatActivity {
11 |
12 | @Override
13 | protected void onCreate(Bundle savedInstanceState) {
14 | super.onCreate(savedInstanceState);
15 | setContentView(R.layout.activity_main);
16 |
17 | Button buttonActivity = findViewById(R.id.buttonActivity);
18 |
19 | buttonActivity.setOnClickListener(new View.OnClickListener() {
20 | @Override
21 | public void onClick(View view) {
22 | startActivity(new Intent(MainActivity.this, ExampleActivity.class));
23 | }
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_example_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ImagePicker
3 | Activity Example
4 | Fragment Example
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:8.1.1'
11 |
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/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 | android.useAndroidX=true
15 | android.enableJetifier=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/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 | apply plugin: 'com.android.library'
2 | apply plugin: 'maven-publish'
3 |
4 | android {
5 | compileSdk 33
6 | buildFeatures.buildConfig true
7 | namespace "in.mayanknagwanshi.imagepicker"
8 | defaultConfig {
9 | minSdkVersion 19
10 | targetSdkVersion 33
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | compileOptions {
23 | sourceCompatibility JavaVersion.VERSION_1_8
24 | targetCompatibility JavaVersion.VERSION_1_8
25 | }
26 | publishing {
27 | singleVariant("release") {
28 | withSourcesJar()
29 | withJavadocJar()
30 | }
31 | }
32 |
33 | }
34 |
35 | dependencies {
36 | implementation 'androidx.appcompat:appcompat:1.2.0'
37 | implementation 'androidx.exifinterface:exifinterface:1.2.0'
38 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
39 | //testImplementation 'junit:junit:4.12'
40 | //androidTestImplementation 'com.android.support.test:runner:1.0.1'
41 | //androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
42 | }
43 |
44 |
45 | publishing {
46 | publications {
47 | release(MavenPublication) {
48 | groupId = 'in.mayanknagwanshi.imagepicker'
49 | artifactId = 'ImagePicker'
50 | version = '1.2.1'
51 |
52 | afterEvaluate {
53 | from components.release
54 | }
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/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/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
19 |
20 |
21 |
26 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/ImageCropActivity.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.os.Bundle;
8 | import android.view.View;
9 | import android.widget.Button;
10 |
11 | import androidx.appcompat.app.AppCompatActivity;
12 |
13 | import java.io.FileNotFoundException;
14 | import java.io.FileOutputStream;
15 |
16 | import in.mayanknagwanshi.imagepicker.view.ImageCropView;
17 |
18 | import static in.mayanknagwanshi.imagepicker.ImageSelectActivity.RESULT_FILE_PATH;
19 |
20 | public class ImageCropActivity extends AppCompatActivity {
21 | private ImageCropView imageCropView;
22 |
23 | @Override
24 | protected void onCreate(Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 | setContentView(R.layout.activity_image_crop);
27 |
28 | imageCropView = findViewById(R.id.imageCropView);
29 | Button buttonContinue = findViewById(R.id.buttonContinue);
30 |
31 | if (getIntent() != null && getIntent().getStringExtra(EXTRA_FILE_PATH) != null) {
32 | Bitmap selectedImage = BitmapFactory.decodeFile(getIntent().getStringExtra(EXTRA_FILE_PATH));
33 | imageCropView.setImageBitmap(selectedImage);
34 | buttonContinue.setOnClickListener(new View.OnClickListener() {
35 | @Override
36 | public void onClick(View v) {
37 | Intent intent = new Intent();
38 | intent.putExtra(RESULT_FILE_PATH, getCroppedPath(getIntent().getStringExtra(EXTRA_FILE_PATH), imageCropView.getCroppedGrid()));
39 | setResult(RESULT_OK, intent);
40 | finish();
41 | }
42 | });
43 | }
44 | }
45 |
46 | private String getCroppedPath(String filePath, ImageCropView.CroppedCoordinate croppedCoordinate) {
47 | Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
48 | Bitmap scaledBitmap = Bitmap.createBitmap(selectedImage, croppedCoordinate.getX(), croppedCoordinate.getY(), croppedCoordinate.getSide(), croppedCoordinate.getSide());
49 | try {
50 | FileOutputStream out = new FileOutputStream(filePath);
51 | scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
52 | } catch (FileNotFoundException e) {
53 | e.printStackTrace();
54 | }
55 | return filePath;
56 | }
57 |
58 | public static final String EXTRA_FILE_PATH = "extra_file_path";
59 |
60 | public static void startActivity(Activity activity, String filePath) {
61 | Intent intent = new Intent(activity, ImageCropActivity.class);
62 | intent.putExtra(EXTRA_FILE_PATH, filePath);
63 | intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
64 | activity.startActivity(intent);
65 | activity.finish();
66 | }
67 | }
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/ImageSelectActivity.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker;
2 |
3 | import android.Manifest;
4 | import android.annotation.TargetApi;
5 | import android.app.Activity;
6 | import android.content.Intent;
7 | import android.content.pm.PackageManager;
8 | import android.os.Build;
9 | import android.os.Bundle;
10 | import android.os.Handler;
11 | import android.os.Looper;
12 | import android.view.View;
13 | import android.view.Window;
14 | import android.widget.ProgressBar;
15 | import android.widget.TextView;
16 |
17 | import androidx.annotation.NonNull;
18 | import androidx.appcompat.app.AppCompatActivity;
19 | import androidx.core.app.ActivityCompat;
20 | import androidx.core.content.ContextCompat;
21 | import androidx.fragment.app.Fragment;
22 |
23 | import in.mayanknagwanshi.imagepicker.imageCompression.ImageCompression;
24 | import in.mayanknagwanshi.imagepicker.imageCompression.ImageCompressionListener;
25 | import in.mayanknagwanshi.imagepicker.imagePicker.ImagePickerUtil;
26 |
27 | public class ImageSelectActivity extends AppCompatActivity {
28 | private static final int EXTERNAL_PERMISSION_CODE = 1234;
29 | public static final int SELECT_IMAGE = 121;
30 |
31 | private ProgressBar progressBar;
32 | private TextView textViewCamera;
33 | private TextView textViewGallery;
34 | private TextView textViewCancel;
35 |
36 | private boolean isCompress = true, isCamera = true, isGallery = true, isCrop = false;
37 |
38 | public static final String FLAG_COMPRESS = "flag_compress";
39 | public static final String FLAG_CAMERA = "flag_camera";
40 | public static final String FLAG_GALLERY = "flag_gallery";
41 | public static final String FLAG_CROP = "flag_crop";
42 |
43 | public static final String RESULT_FILE_PATH = "result_file_path";
44 |
45 | @Override
46 | protected void onCreate(Bundle savedInstanceState) {
47 | super.onCreate(savedInstanceState);
48 | supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
49 | setContentView(R.layout.activity_image_select);
50 |
51 | progressBar = findViewById(R.id.progressBar);
52 | textViewCamera = findViewById(R.id.textViewCamera);
53 | textViewGallery = findViewById(R.id.textViewGallery);
54 | textViewCancel = findViewById(R.id.textViewCancel);
55 |
56 | textViewCancel.setOnClickListener(new View.OnClickListener() {
57 | @Override
58 | public void onClick(View v) {
59 | setResult(RESULT_CANCELED);
60 | finish();
61 | }
62 | });
63 | textViewCamera.setOnClickListener(new View.OnClickListener() {
64 | @Override
65 | public void onClick(View v) {
66 | if (checkPermission()) {
67 | toggleProgress(true);
68 | startActivityForResult(ImagePickerUtil.getPickImageChooserIntent(ImageSelectActivity.this, true, false), SELECT_IMAGE);
69 | } else {
70 | requestStoragePermission();
71 | }
72 | }
73 | });
74 | textViewGallery.setOnClickListener(new View.OnClickListener() {
75 | @Override
76 | public void onClick(View v) {
77 | if (checkPermission()) {
78 | toggleProgress(true);
79 | startActivityForResult(ImagePickerUtil.getPickImageChooserIntent(ImageSelectActivity.this, false, true), SELECT_IMAGE);
80 | } else {
81 | requestStoragePermission();
82 | }
83 | }
84 | });
85 |
86 | if (getIntent() != null) {
87 | isCompress = getIntent().getBooleanExtra(FLAG_COMPRESS, true);
88 | isCamera = getIntent().getBooleanExtra(FLAG_CAMERA, true);
89 | isGallery = getIntent().getBooleanExtra(FLAG_GALLERY, true);
90 | isCrop = getIntent().getBooleanExtra(FLAG_CROP, false);
91 | }
92 |
93 | if (isCamera && isGallery) toggleProgress(false);
94 | else toggleProgress(true);
95 |
96 | if (checkPermission() && (!isCamera || !isGallery)) {
97 | //start image picker
98 | startActivityForResult(ImagePickerUtil.getPickImageChooserIntent(ImageSelectActivity.this, isCamera, isGallery), SELECT_IMAGE);
99 | } else {
100 | //ask permission
101 | requestStoragePermission();
102 | }
103 | }
104 |
105 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
106 | private boolean checkPermission() {
107 | int currentAPIVersion = Build.VERSION.SDK_INT;
108 | return currentAPIVersion >= Build.VERSION_CODES.TIRAMISU ? (ContextCompat.checkSelfPermission(this,
109 | Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
110 | && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
111 | PackageManager.PERMISSION_GRANTED) : (ContextCompat.checkSelfPermission(this,
112 | Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
113 | && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
114 | PackageManager.PERMISSION_GRANTED);
115 | }
116 |
117 | private void requestStoragePermission() {
118 | ActivityCompat.requestPermissions(this, Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
119 | ? new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.CAMERA}
120 | : new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
121 | EXTERNAL_PERMISSION_CODE);
122 | }
123 |
124 | @Override
125 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
126 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
127 | if (requestCode == EXTERNAL_PERMISSION_CODE) {
128 | if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
129 | if ((!isCamera || !isGallery))
130 | startActivityForResult(ImagePickerUtil.getPickImageChooserIntent(ImageSelectActivity.this, isCamera, isGallery), SELECT_IMAGE);
131 | } else {
132 | setResult(RESULT_CANCELED);
133 | finish();
134 | }
135 | }
136 | }
137 |
138 | @Override
139 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
140 | super.onActivityResult(requestCode, resultCode, data);
141 | if (requestCode == SELECT_IMAGE) {
142 | if (resultCode == RESULT_OK) {
143 | sendResult(data);
144 | } else {
145 | setResult(RESULT_CANCELED);
146 | finish();
147 | }
148 | }
149 | }
150 |
151 | private void sendResult(final Intent data) {
152 | //add delay
153 | new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
154 | @Override
155 | public void run() {
156 | String filePath = ImagePickerUtil.getImageFilePath(ImageSelectActivity.this, data);
157 | if (filePath != null && !isCompress) {
158 | //return filepath
159 | sendResult(filePath);
160 | return;
161 | }
162 |
163 | new ImageCompression(ImageSelectActivity.this, filePath, new ImageCompressionListener() {
164 | @Override
165 | public void onCompressed(String filePath) {
166 | if (filePath != null && isCompress) {
167 | //return filepath
168 | sendResult(filePath);
169 | }
170 | }
171 | }).execute();
172 | }
173 | }, 1000);
174 | }
175 |
176 | private void sendResult(String filePath) {
177 | if (!isCrop) {
178 | Intent intent = new Intent();
179 | intent.putExtra(RESULT_FILE_PATH, filePath);
180 | setResult(RESULT_OK, intent);
181 | finish();
182 | } else
183 | ImageCropActivity.startActivity(ImageSelectActivity.this, filePath);
184 | }
185 |
186 | private void toggleProgress(boolean showProgress) {
187 | progressBar.setVisibility(showProgress ? View.VISIBLE : View.GONE);
188 | textViewCamera.setVisibility(showProgress ? View.GONE : View.VISIBLE);
189 | textViewGallery.setVisibility(showProgress ? View.GONE : View.VISIBLE);
190 | textViewCancel.setVisibility(showProgress ? View.GONE : View.VISIBLE);
191 | }
192 |
193 | //region init
194 | public static void startImageSelectionForResult(Activity activity, boolean isCamera, boolean isGallery, boolean isCompress, boolean isCrop, int requestCode) {
195 | Intent intent = new Intent(activity, ImageSelectActivity.class);
196 | intent.putExtra(ImageSelectActivity.FLAG_CAMERA, isCamera);
197 | intent.putExtra(ImageSelectActivity.FLAG_GALLERY, isGallery);
198 | intent.putExtra(ImageSelectActivity.FLAG_COMPRESS, isCompress);
199 | intent.putExtra(ImageSelectActivity.FLAG_CROP, isCrop);
200 | activity.startActivityForResult(intent, requestCode);
201 | }
202 |
203 | public static void startImageSelectionForResult(Fragment fragment, boolean isCamera, boolean isGallery, boolean isCompress, boolean isCrop, int requestCode) {
204 | Intent intent = new Intent(fragment.getContext(), ImageSelectActivity.class);
205 | intent.putExtra(ImageSelectActivity.FLAG_CAMERA, isCamera);
206 | intent.putExtra(ImageSelectActivity.FLAG_GALLERY, isGallery);
207 | intent.putExtra(ImageSelectActivity.FLAG_COMPRESS, isCompress);
208 | intent.putExtra(ImageSelectActivity.FLAG_CROP, isCrop);
209 | fragment.startActivityForResult(intent, requestCode);
210 | }
211 | //endregion
212 | }
213 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/imageCompression/ImageCompression.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.imageCompression;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.Context;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.graphics.Canvas;
8 | import android.graphics.Matrix;
9 | import android.graphics.Paint;
10 | import android.os.AsyncTask;
11 |
12 | import androidx.exifinterface.media.ExifInterface;
13 |
14 | import java.io.File;
15 | import java.io.FileNotFoundException;
16 | import java.io.FileOutputStream;
17 | import java.io.IOException;
18 |
19 | public class ImageCompression extends AsyncTask {
20 | private final String filePath;
21 | private final ImageCompressionListener imageCompressionListener;
22 |
23 | @SuppressLint("StaticFieldLeak")
24 | private final Context context;
25 | private static final float maxHeight = 1280.0f;
26 | private static final float maxWidth = 1280.0f;
27 |
28 |
29 | public ImageCompression(Context context, String filePath, ImageCompressionListener imageCompressionListener) {
30 | this.context = context;
31 | this.filePath = filePath;
32 | this.imageCompressionListener = imageCompressionListener;
33 | }
34 |
35 | @Override
36 | protected void onPreExecute() {
37 | super.onPreExecute();
38 | }
39 |
40 | @Override
41 | protected String doInBackground(Void... strings) {
42 | return compressImage(filePath);
43 | }
44 |
45 | protected void onPostExecute(String imagePath) {
46 | // imagePath is path of new compressed image.
47 | imageCompressionListener.onCompressed(imagePath);
48 | }
49 |
50 |
51 | private String compressImage(String imagePath) {
52 | Bitmap scaledBitmap = null;
53 |
54 | BitmapFactory.Options options = new BitmapFactory.Options();
55 | options.inJustDecodeBounds = true;
56 | Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
57 |
58 | int actualHeight = options.outHeight;
59 | int actualWidth = options.outWidth;
60 |
61 | float imgRatio = (float) actualWidth / (float) actualHeight;
62 | float maxRatio = maxWidth / maxHeight;
63 |
64 | if (actualHeight > maxHeight || actualWidth > maxWidth) {
65 | if (imgRatio < maxRatio) {
66 | imgRatio = maxHeight / actualHeight;
67 | actualWidth = (int) (imgRatio * actualWidth);
68 | actualHeight = (int) maxHeight;
69 | } else if (imgRatio > maxRatio) {
70 | imgRatio = maxWidth / actualWidth;
71 | actualHeight = (int) (imgRatio * actualHeight);
72 | actualWidth = (int) maxWidth;
73 | } else {
74 | actualHeight = (int) maxHeight;
75 | actualWidth = (int) maxWidth;
76 | }
77 | }
78 |
79 | options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
80 | options.inJustDecodeBounds = false;
81 | options.inDither = false;
82 | options.inPurgeable = true;
83 | options.inInputShareable = true;
84 | options.inTempStorage = new byte[16 * 1024];
85 |
86 | try {
87 | bmp = BitmapFactory.decodeFile(imagePath, options);
88 | } catch (OutOfMemoryError exception) {
89 | exception.printStackTrace();
90 |
91 | }
92 | try {
93 | scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);
94 | } catch (OutOfMemoryError exception) {
95 | exception.printStackTrace();
96 | }
97 |
98 | float ratioX = actualWidth / (float) options.outWidth;
99 | float ratioY = actualHeight / (float) options.outHeight;
100 | float middleX = actualWidth / 2.0f;
101 | float middleY = actualHeight / 2.0f;
102 |
103 | Matrix scaleMatrix = new Matrix();
104 | scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
105 |
106 | Canvas canvas = new Canvas(scaledBitmap);
107 | canvas.setMatrix(scaleMatrix);
108 | canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
109 |
110 | bmp.recycle();
111 |
112 | ExifInterface exif;
113 | try {
114 | exif = new ExifInterface(imagePath);
115 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
116 | Matrix matrix = new Matrix();
117 | switch (orientation) {
118 | case 6:
119 | matrix.postRotate(90);
120 | break;
121 | case 3:
122 | matrix.postRotate(180);
123 | break;
124 | case 8:
125 | matrix.postRotate(270);
126 | break;
127 | }
128 | scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
129 | } catch (IOException e) {
130 | e.printStackTrace();
131 | }
132 | FileOutputStream out;
133 | String filepath = getFilename();
134 | try {
135 | out = new FileOutputStream(filepath);
136 |
137 | //write the compressed bitmap at the destination specified by filename.
138 | scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
139 |
140 | } catch (FileNotFoundException e) {
141 | e.printStackTrace();
142 | }
143 |
144 | return filepath;
145 | }
146 |
147 | private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
148 | final int height = options.outHeight;
149 | final int width = options.outWidth;
150 | int inSampleSize = 1;
151 |
152 | if (height > reqHeight || width > reqWidth) {
153 | final int heightRatio = Math.round((float) height / (float) reqHeight);
154 | final int widthRatio = Math.round((float) width / (float) reqWidth);
155 | inSampleSize = Math.min(heightRatio, widthRatio);
156 | }
157 | final float totalPixels = width * height;
158 | final float totalReqPixelsCap = reqWidth * reqHeight * 2;
159 |
160 | while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
161 | inSampleSize++;
162 | }
163 |
164 | return inSampleSize;
165 | }
166 |
167 | private String getFilename() {
168 | File mediaStorageDir = new File(context.getExternalFilesDir(""), "compressed");
169 |
170 | // Create the storage directory if it does not exist
171 | if (!mediaStorageDir.exists()) {
172 | mediaStorageDir.mkdirs();
173 | }
174 |
175 | String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
176 | return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
177 |
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/imageCompression/ImageCompressionListener.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.imageCompression;
2 |
3 | public interface ImageCompressionListener {
4 | void onCompressed(String filePath);
5 | }
6 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/imagePicker/ImagePickerUtil.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.imagePicker;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.os.Parcelable;
7 | import android.provider.MediaStore;
8 |
9 | import java.io.ByteArrayOutputStream;
10 | import java.io.File;
11 | import java.io.FileOutputStream;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.io.OutputStream;
15 | import java.util.ArrayList;
16 | import java.util.List;
17 |
18 | import in.mayanknagwanshi.imagepicker.provider.ImageSelectionProvider;
19 |
20 | public class ImagePickerUtil {
21 | static String filePath;
22 |
23 | public static Intent getPickImageChooserIntent(Context context, boolean isCamera, boolean isGallery) {
24 | // Determine Uri of camera image to save.
25 | Uri outputFileUri = getCaptureImageOutputUri(context);
26 |
27 | List allIntents = new ArrayList<>();
28 | //PackageManager packageManager = context.getPackageManager();
29 |
30 | if (isCamera) {
31 | // collect all camera intents
32 | Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
33 | captureIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
34 | if (outputFileUri != null) {
35 | captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
36 | }
37 | allIntents.add(captureIntent);
38 | }
39 |
40 | if (isGallery) {
41 | // collect all gallery intents
42 | Intent galleryIntent = new Intent();
43 | galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
44 | galleryIntent.setType("image/*");
45 | galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
46 | allIntents.add(galleryIntent);
47 | }
48 |
49 | Intent mainIntent = allIntents.get(allIntents.size() - 1);
50 | for (Intent intent : allIntents) {
51 | if (intent.getComponent() != null && intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
52 | mainIntent = intent;
53 | break;
54 | }
55 | }
56 | allIntents.remove(mainIntent);
57 |
58 | // Create a chooser from the main intent
59 | Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
60 |
61 | // Add all other intents
62 | chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
63 |
64 | return chooserIntent;
65 | }
66 |
67 | private static Uri getCaptureImageOutputUri(Context context) {
68 | Uri outputFileUri = null;
69 | File getImage = context.getExternalFilesDir("");
70 | if (getImage != null) {
71 | //outputFileUri = Uri.fromFile(new File(getImage.getPath(), "profile.png"));
72 | String fileName = "IMG_" + System.currentTimeMillis() + ".png";
73 | filePath = new File(getImage.getPath(), fileName).getPath();
74 | outputFileUri = ImageSelectionProvider.getUriForFile(context,
75 | context.getPackageName() + ".image-selection-provider",
76 | new File(getImage.getPath(), fileName));
77 | }
78 | return outputFileUri;
79 | }
80 |
81 | public static String getImageFilePath(Context context, Intent data) {
82 | return getPickImageResultFilePath(context, data);
83 | }
84 |
85 | private static String getPickImageResultFilePath(Context context, Intent data) {
86 | boolean isCamera = data == null || data.getData() == null;
87 | //Log.e("data", +"");
88 | /*if (data != null) {
89 | isCamera = false;
90 | String action = data.getAction();
91 | isCamera = action != null && action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
92 | } else {
93 | isCamera = true;
94 | }*/
95 |
96 | //Log.e("isCamera", isCamera ? "true" : "false");
97 | if (isCamera) return filePath;
98 | else return getRealPathFromURI(context, data.getData());
99 | //return isCamera ? getCaptureImageOutputUri() : data.getData();
100 | }
101 |
102 | private static String getRealPathFromURI(Context context, Uri contentUri) {
103 | /*String[] proj = {MediaStore.Audio.Media.DATA};
104 | Cursor cursor = activity != null ?
105 | activity.getContentResolver().query(contentUri, proj, null, null, null) : fragment.getActivity().getContentResolver().query(contentUri, proj, null, null, null);
106 | int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
107 | cursor.moveToFirst();
108 | return cursor.getString(column_index);*/
109 |
110 | OutputStream out;
111 | File file = new File(getFilename(context));
112 |
113 | try {
114 | if (file.createNewFile()) {
115 | InputStream iStream = context.getContentResolver().openInputStream(contentUri);
116 | byte[] inputData = getBytes(iStream);
117 | out = new FileOutputStream(file);
118 | out.write(inputData);
119 | out.close();
120 | return file.getAbsolutePath();
121 | }
122 | } catch (IOException e) {
123 | e.printStackTrace();
124 | }
125 | return null;
126 | }
127 |
128 | private static byte[] getBytes(InputStream inputStream) throws IOException {
129 | ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
130 | int bufferSize = 1024;
131 | byte[] buffer = new byte[bufferSize];
132 |
133 | int len = 0;
134 | while ((len = inputStream.read(buffer)) != -1) {
135 | byteBuffer.write(buffer, 0, len);
136 | }
137 | return byteBuffer.toByteArray();
138 | }
139 |
140 | private static String getFilename(Context context) {
141 | File mediaStorageDir = new File(context.getExternalFilesDir(""), "uncompressed");
142 |
143 | //File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Compressed");
144 |
145 | // Create the storage directory if it does not exist
146 | if (!mediaStorageDir.exists()) {
147 | mediaStorageDir.mkdirs();
148 | }
149 |
150 | String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
151 | return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
152 |
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/provider/ImageSelectionProvider.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.provider;
2 |
3 | import androidx.core.content.FileProvider;
4 |
5 | public class ImageSelectionProvider extends FileProvider {
6 | }
7 |
--------------------------------------------------------------------------------
/imagepicker/src/main/java/in/mayanknagwanshi/imagepicker/view/ImageCropView.java:
--------------------------------------------------------------------------------
1 | package in.mayanknagwanshi.imagepicker.view;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.Context;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.graphics.Canvas;
8 | import android.graphics.Paint;
9 | import android.graphics.Rect;
10 | import android.util.AttributeSet;
11 | import android.view.MotionEvent;
12 |
13 | import androidx.annotation.NonNull;
14 | import androidx.annotation.Nullable;
15 | import androidx.appcompat.widget.AppCompatImageView;
16 |
17 | import in.mayanknagwanshi.imagepicker.R;
18 |
19 | public class ImageCropView extends AppCompatImageView {
20 | private Paint paint;
21 | private Bitmap bitmapGrid;
22 | private int maxHeight = 0, maxWidth = 0;
23 | private Rect rectCropGrid;
24 | private int sideLengthRect = 0;
25 | private int downTouchX = 0, downTouchY = 0;
26 | private int downTouchToMoveX = 0, downTouchToMoveY = 0;
27 | private int rectLeft = 0, rectTop = 0;
28 | private boolean isImageSet = false;
29 |
30 | public ImageCropView(@NonNull Context context) {
31 | this(context, null);
32 | }
33 |
34 | public ImageCropView(@NonNull Context context, @Nullable AttributeSet attrs) {
35 | this(context, attrs, 0);
36 | }
37 |
38 | public ImageCropView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
39 | super(context, attrs, defStyleAttr);
40 | init();
41 | }
42 |
43 | private void init() {
44 | bitmapGrid = BitmapFactory.decodeResource(getResources(), R.drawable.frame);
45 | paint = new Paint();
46 | paint.setAlpha(255);
47 | }
48 |
49 | @Override
50 | public void onDraw(Canvas canvas) {
51 | super.onDraw(canvas);
52 | if (getDrawable() == null) return;
53 | if (!isImageSet) {
54 | initCalc();
55 | isImageSet = true;
56 | }
57 | drawCropper(canvas);
58 | }
59 |
60 | private void drawCropper(Canvas canvas) {
61 | if (sideLengthRect == 0)
62 | sideLengthRect = Math.min(maxWidth, maxHeight) / 2;
63 |
64 | if (rectCropGrid == null)
65 | rectCropGrid = new Rect(rectLeft, rectTop, sideLengthRect, sideLengthRect);
66 |
67 | canvas.drawBitmap(bitmapGrid, null, rectCropGrid, paint);
68 | }
69 |
70 | private void initCalc() {
71 | /*int viewHeight = getMeasuredHeight();//height of imageView
72 | int viewWidth = getMeasuredWidth();//width of imageView
73 |
74 | maxHeight = getDrawable().getIntrinsicHeight();//original height of underlying image
75 | maxWidth = getDrawable().getIntrinsicWidth();//original width of underlying image
76 |
77 | maxWidth = maxWidth * viewHeight / maxHeight;
78 | maxHeight = maxHeight * viewWidth / maxWidth;
79 | if (viewHeight / maxHeight <= viewWidth / maxWidth) {
80 | viewWidth = maxWidth * viewHeight / maxHeight;//rescaled width of image within ImageView
81 | } else {
82 | viewHeight = maxHeight * viewWidth / maxWidth;//rescaled height of image within ImageView
83 | }*/
84 |
85 | maxHeight = getMeasuredHeight();
86 | maxWidth = getMeasuredWidth();
87 |
88 | if (getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth() > maxHeight / maxWidth) {
89 | //image view width greater than bitmap width
90 | maxWidth = (int) ((maxHeight * 1.0 / getDrawable().getIntrinsicHeight()) * getDrawable().getIntrinsicWidth());
91 | }
92 | }
93 |
94 | @Override
95 | public void setImageBitmap(Bitmap bm) {
96 | super.setImageBitmap(bm);
97 | isImageSet = false;
98 | }
99 |
100 | @SuppressLint("ClickableViewAccessibility")
101 | @Override
102 | public boolean onTouchEvent(MotionEvent event) {
103 | if (rectCropGrid == null) return super.onTouchEvent(event);
104 | switch (event.getAction()) {
105 | case MotionEvent.ACTION_DOWN:
106 | int eventX = (int) event.getX();
107 | int eventY = (int) event.getY();
108 | if (getCornerPaddedRect(rectCropGrid.right, rectCropGrid.bottom).contains(eventX, eventY)) {
109 | downTouchToMoveX = eventX;
110 | downTouchToMoveY = eventY;
111 | } else if (rectCropGrid.contains(eventX, eventY)) {
112 | downTouchX = eventX;
113 | downTouchY = eventY;
114 | } else {
115 | downTouchX = 0;
116 | downTouchY = 0;
117 | downTouchToMoveX = 0;
118 | downTouchToMoveY = 0;
119 | }
120 | break;
121 | case MotionEvent.ACTION_MOVE:
122 | if (downTouchToMoveX != 0 && downTouchToMoveY != 0) {
123 | int moveX = (int) event.getX();
124 | int moveY = (int) event.getY();
125 | int displacementX = moveX - downTouchToMoveX;
126 | int displacementY = moveY - downTouchToMoveY;
127 | int displacement = Math.max(displacementX, displacementY);
128 | if (rectLeft + displacement + sideLengthRect <= maxWidth && rectTop + displacement + sideLengthRect <= maxHeight &&
129 | sideLengthRect + displacement < Math.min(maxWidth, maxHeight) && sideLengthRect + displacement > Math.min(maxWidth, maxHeight) / 4) {
130 | sideLengthRect += displacement;
131 | rectCropGrid.set(rectLeft, rectTop, sideLengthRect + rectLeft, sideLengthRect + rectTop);
132 | }
133 | downTouchToMoveX = (int) event.getX();
134 | downTouchToMoveY = (int) event.getY();
135 | invalidate();
136 | }
137 | if (downTouchX == 0 && downTouchY == 0) break;
138 | int moveX = (int) event.getX();
139 | int moveY = (int) event.getY();
140 | int displacementX = moveX - downTouchX;
141 | int displacementY = moveY - downTouchY;
142 | if ((rectLeft + displacementX + sideLengthRect <= maxWidth && rectLeft + displacementX >= 0) && (rectTop + displacementY + sideLengthRect <= maxHeight && rectTop + displacementY >= 0)) {
143 | rectTop += displacementY;
144 | rectLeft += displacementX;
145 | rectCropGrid.set(rectLeft, rectTop, sideLengthRect + rectLeft, sideLengthRect + rectTop);
146 | downTouchX = (int) event.getX();
147 | downTouchY = (int) event.getY();
148 | }
149 | invalidate();
150 | break;
151 | case MotionEvent.ACTION_UP:
152 | downTouchX = 0;
153 | downTouchY = 0;
154 | downTouchToMoveX = 0;
155 | downTouchToMoveY = 0;
156 | break;
157 | }
158 | return true;
159 | }
160 |
161 | private Rect getCornerPaddedRect(int x, int y) {
162 | int paddingRadius = sideLengthRect / 10;
163 | return new Rect(x - paddingRadius, y - paddingRadius, x + paddingRadius, y + paddingRadius);
164 | }
165 |
166 | public CroppedCoordinate getCroppedGrid() {
167 | //scale grid before returning
168 | double scaleFactor = getDrawable().getIntrinsicWidth() * 1.0 / maxWidth;
169 | return new CroppedCoordinate((int) (rectCropGrid.left * scaleFactor), (int) (rectCropGrid.top * scaleFactor), (int) (sideLengthRect * scaleFactor));
170 | }
171 |
172 | public static class CroppedCoordinate {
173 | int x, y, side;
174 |
175 | public CroppedCoordinate(int x, int y, int side) {
176 | this.x = x;
177 | this.y = y;
178 | this.side = side;
179 | }
180 |
181 | public int getX() {
182 | return x;
183 | }
184 |
185 | public int getY() {
186 | return y;
187 | }
188 |
189 | public int getSide() {
190 | return side;
191 | }
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/imagepicker/src/main/res/drawable-nodpi/frame.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/imagepicker/src/main/res/drawable-nodpi/frame.png
--------------------------------------------------------------------------------
/imagepicker/src/main/res/layout/activity_image_crop.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
29 |
--------------------------------------------------------------------------------
/imagepicker/src/main/res/layout/activity_image_select.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
29 |
30 |
40 |
41 |
48 |
--------------------------------------------------------------------------------
/imagepicker/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ImagePicker
3 |
4 |
--------------------------------------------------------------------------------
/imagepicker/src/main/res/xml/provider_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | -openjdk20
--------------------------------------------------------------------------------
/sample.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maayyaannkk/ImagePicker/b5aa8ca1b0344c8fdef32240b789d5088488d9a5/sample.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':imagepicker'
2 |
--------------------------------------------------------------------------------