├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ ├── adapter_image.xml
│ │ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── donkingliang
│ │ │ └── imageselectdemo
│ │ │ ├── adapter
│ │ │ └── ImageAdapter.java
│ │ │ └── MainActivity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── donkingliang
│ │ │ └── imageselectdemo
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── donkingliang
│ │ └── imageselectdemo
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── imageselector
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable-xhdpi
│ │ │ │ ├── ic_gif.png
│ │ │ │ ├── icon_back.png
│ │ │ │ ├── text_indicator.png
│ │ │ │ ├── ic_photo_camera.png
│ │ │ │ ├── icon_image_select.png
│ │ │ │ └── icon_image_un_select.png
│ │ │ ├── drawable
│ │ │ │ ├── btn_green_shape.xml
│ │ │ │ ├── btn_back_selector.xml
│ │ │ │ ├── btn_foreground_selector.xml
│ │ │ │ └── folder_bg.xml
│ │ │ ├── xml
│ │ │ │ └── image_selector_file_paths.xml
│ │ │ ├── layout
│ │ │ │ ├── adapter_camera.xml
│ │ │ │ ├── adapter_images_item.xml
│ │ │ │ ├── adapter_folder.xml
│ │ │ │ ├── activity_clip_image.xml
│ │ │ │ ├── activity_preview.xml
│ │ │ │ └── activity_image_select.xml
│ │ │ ├── values
│ │ │ │ └── strings.xml
│ │ │ └── values-en
│ │ │ │ └── strings.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── donkingliang
│ │ │ │ └── imageselector
│ │ │ │ ├── provider
│ │ │ │ └── ImageSelectorProvider.java
│ │ │ │ ├── utils
│ │ │ │ ├── StringUtils.java
│ │ │ │ ├── VersionUtils.java
│ │ │ │ ├── MD5Utils.java
│ │ │ │ ├── DateUtils.java
│ │ │ │ ├── ImageSelector.java
│ │ │ │ ├── UriUtils.java
│ │ │ │ └── ImageUtil.java
│ │ │ │ ├── view
│ │ │ │ ├── SquareImageView.java
│ │ │ │ ├── MyViewPager.java
│ │ │ │ └── ClipImageView.java
│ │ │ │ ├── entry
│ │ │ │ ├── Folder.java
│ │ │ │ ├── RequestConfig.java
│ │ │ │ └── Image.java
│ │ │ │ ├── adapter
│ │ │ │ ├── FolderAdapter.java
│ │ │ │ ├── ImagePagerAdapter.java
│ │ │ │ └── ImageAdapter.java
│ │ │ │ ├── ClipImageActivity.java
│ │ │ │ ├── model
│ │ │ │ └── ImageModel.java
│ │ │ │ ├── PreviewActivity.java
│ │ │ │ └── ImageSelectorActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── donkingliang
│ │ │ └── imageselector
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── donkingliang
│ │ └── imageselector
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── 效果图
├── 相册.jpg
├── 预览.jpg
└── 文件夹.jpg
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README1.4.0.md
├── gradlew
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/imageselector/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':imageselector'
2 |
--------------------------------------------------------------------------------
/效果图/相册.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/效果图/相册.jpg
--------------------------------------------------------------------------------
/效果图/预览.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/效果图/预览.jpg
--------------------------------------------------------------------------------
/效果图/文件夹.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/效果图/文件夹.jpg
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ImageSelectDemo
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/ic_gif.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/ic_gif.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/icon_back.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/icon_back.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/text_indicator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/text_indicator.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/ic_photo_camera.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/ic_photo_camera.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/icon_image_select.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/icon_image_select.png
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable-xhdpi/icon_image_un_select.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/donkingliang/ImageSelector/HEAD/imageselector/src/main/res/drawable-xhdpi/icon_image_un_select.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable/btn_green_shape.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/xml/image_selector_file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/provider/ImageSelectorProvider.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.provider;
2 |
3 | import androidx.core.content.FileProvider;
4 |
5 | /**
6 | * @Author teach liang
7 | * @Description
8 | * @Date 2019/9/12
9 | */
10 | public class ImageSelectorProvider extends FileProvider {
11 |
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/StringUtils.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | public class StringUtils {
4 |
5 | public static boolean isNotEmptyString(final String str) {
6 | return str != null && str.length() > 0;
7 | }
8 |
9 | public static boolean isEmptyString(final String str) {
10 | return str == null || str.length() <= 0;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/test/java/com/donkingliang/imageselectdemo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselectdemo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/imageselector/src/test/java/com/donkingliang/imageselector/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/donkingliang/imageselectdemo/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselectdemo;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/imageselector/src/androidTest/java/com/donkingliang/imageselector/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | /captures
3 |
4 | # Built application files
5 | *.apk
6 | *.ap_
7 |
8 |
9 |
10 | # Generated files
11 | bin/
12 | gen/
13 |
14 | # Gradle files
15 | .gradle/
16 | /build
17 | /*/build/
18 |
19 | # Local configuration file (sdk path, etc)
20 | local.properties
21 |
22 | # Proguard folder generated by Eclipse
23 | proguard/
24 |
25 | # Log Files
26 | *.log
27 |
28 | # Eclipse project files
29 | .classpath
30 | .project
31 | .settings/
32 |
33 | # Intellij project files
34 | *.iml
35 | *.ipr
36 | *.iws
37 | .idea/
38 |
39 | # System files
40 | .DS_Store
--------------------------------------------------------------------------------
/app/src/main/res/layout/adapter_image.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
16 |
--------------------------------------------------------------------------------
/imageselector/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
10 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\Administrator\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/adapter_camera.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
--------------------------------------------------------------------------------
/imageselector/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\Administrator\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable/btn_back_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 | -
10 |
11 |
12 |
13 |
14 |
15 | -
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable/btn_foreground_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 | -
10 |
11 |
12 |
13 |
14 |
15 | -
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 图片
3 | 确定
4 | 预览
5 | 选择
6 | %d张
7 | 全部图片
8 | 今天
9 | 本周
10 | 本月
11 | 确定
12 | 取消
13 | 提示
14 | 该相册需要赋予访问存储和拍照的权限,请到“设置”>“应用”>“权限”中配置权限。
15 |
16 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/drawable/folder_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
7 |
8 |
11 |
12 |
13 |
14 |
15 | -
20 |
21 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/view/SquareImageView.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.view;
2 |
3 | import android.content.Context;
4 | import androidx.appcompat.widget.AppCompatImageView;
5 | import android.util.AttributeSet;
6 |
7 | /**
8 | * 正方形的ImageView
9 | */
10 | public class SquareImageView extends AppCompatImageView {
11 |
12 | public SquareImageView(Context context) {
13 | super(context);
14 | }
15 |
16 | public SquareImageView(Context context, AttributeSet attrs) {
17 | super(context, attrs);
18 | }
19 |
20 | public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
21 | super(context, attrs, defStyleAttr);
22 | }
23 |
24 | @Override
25 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
26 | super.onMeasure(widthMeasureSpec, widthMeasureSpec);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/values-en/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Photos
3 | Send
4 | Preview
5 | Select
6 | %d
7 | All Photos
8 | This today
9 | This week
10 | This month
11 | Confirm
12 | Cancel
13 | Hint
14 | This album needs to be granted access to storage and photos, please go to Settings > App > Permissions to configure permissions.
15 |
16 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/view/MyViewPager.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.view;
2 |
3 | import android.content.Context;
4 | import androidx.viewpager.widget.ViewPager;
5 | import android.util.AttributeSet;
6 | import android.view.MotionEvent;
7 |
8 | /**
9 | * 继承ViewPager并在onInterceptTouchEvent捕捉异常。
10 | * 因为ViewPager嵌套PhotoView使用,有时候会发生IllegalArgumentException异常。
11 | */
12 | public class MyViewPager extends ViewPager {
13 |
14 | public MyViewPager(Context context) {
15 | super(context);
16 | }
17 |
18 | public MyViewPager(Context context, AttributeSet attrs) {
19 | super(context, attrs);
20 | }
21 |
22 | @Override
23 | public boolean onInterceptTouchEvent(MotionEvent ev) {
24 | try {
25 | return super.onInterceptTouchEvent(ev);
26 | } catch (IllegalArgumentException e) {
27 | return false;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | defaultConfig {
6 | applicationId "com.donkingliang.imageselectdemo"
7 | minSdkVersion 14
8 | targetSdkVersion 30
9 | versionCode 1
10 | versionName "1.0"
11 | }
12 | buildTypes {
13 | release {
14 | minifyEnabled false
15 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
16 | }
17 | }
18 | }
19 |
20 | dependencies {
21 | implementation fileTree(dir: 'libs', include: ['*.jar'])
22 | testImplementation 'junit:junit:4.12'
23 | implementation 'androidx.appcompat:appcompat:1.2.0'
24 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
25 | implementation 'com.github.bumptech.glide:glide:4.12.0'
26 | annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
27 | implementation project(':imageselector')
28 | }
29 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 | android.enableJetifier=true
20 | android.useAndroidX=true
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/VersionUtils.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import android.os.Build;
4 |
5 | /**
6 | * @Author teach-梁任彦
7 | * @Description
8 | * @Date 2019-09-11
9 | */
10 | public class VersionUtils {
11 |
12 | /**
13 | * 判断是否是Android L版本
14 | *
15 | * @return
16 | */
17 | public static boolean isAndroidL() {
18 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
19 | }
20 |
21 | /**
22 | * 判断是否是Android N版本
23 | *
24 | * @return
25 | */
26 | public static boolean isAndroidN() {
27 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
28 | }
29 |
30 | /**
31 | * 判断是否是Android P版本
32 | *
33 | * @return
34 | */
35 | public static boolean isAndroidP() {
36 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
37 | }
38 |
39 | /**
40 | * 判断是否是Android Q版本
41 | *
42 | * @return
43 | */
44 | public static boolean isAndroidQ() {
45 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/MD5Utils.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import java.security.MessageDigest;
4 |
5 | /**
6 | * @Author teach liang
7 | * @Description MD5工具类
8 | * @Date 2019/1/2
9 | */
10 | public class MD5Utils {
11 |
12 | private static final String HEX_DIGITS[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
13 |
14 | public static String md5(String s) {
15 | try {
16 | MessageDigest md = MessageDigest.getInstance("MD5");
17 | byte[] bytes = md.digest(s.getBytes("utf-8"));
18 | return toHex(bytes);
19 | } catch (Exception e) {
20 | e.printStackTrace();
21 | }
22 | return null;
23 | }
24 |
25 | private static String toHex(byte[] bytes) {
26 | StringBuilder ret = new StringBuilder(bytes.length * 2);
27 | for (int i = 0; i < bytes.length; i++) {
28 | ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
29 | ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
30 | }
31 | return ret.toString();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/adapter_images_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
16 |
22 |
23 |
33 |
34 |
42 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/entry/Folder.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.entry;
2 |
3 |
4 | import com.donkingliang.imageselector.utils.StringUtils;
5 |
6 | import java.util.ArrayList;
7 |
8 | /**
9 | * 图片文件夹实体类
10 | */
11 | public class Folder {
12 |
13 | private boolean useCamera; // 是否可以调用相机拍照。只有“全部”文件夹才可以拍照
14 | private String name;
15 | private ArrayList images;
16 |
17 | public Folder(String name) {
18 | this.name = name;
19 | }
20 |
21 | public Folder(String name, ArrayList images) {
22 | this.name = name;
23 | this.images = images;
24 | }
25 |
26 | public String getName() {
27 | return name;
28 | }
29 |
30 | public void setName(String name) {
31 | this.name = name;
32 | }
33 |
34 | public ArrayList getImages() {
35 | return images;
36 | }
37 |
38 | public void setImages(ArrayList images) {
39 | this.images = images;
40 | }
41 |
42 | public boolean isUseCamera() {
43 | return useCamera;
44 | }
45 |
46 | public void setUseCamera(boolean useCamera) {
47 | this.useCamera = useCamera;
48 | }
49 |
50 | public void addImage(Image image) {
51 | if (image != null && StringUtils.isNotEmptyString(image.getPath())) {
52 | if (images == null) {
53 | images = new ArrayList<>();
54 | }
55 | images.add(image);
56 | }
57 | }
58 |
59 | @Override
60 | public String toString() {
61 | return "Folder{" +
62 | "name='" + name + '\'' +
63 | ", images=" + images +
64 | '}';
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
26 |
30 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/imageselector/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | group='com.github.donkingliang' // 指定group,com.github.<用户名>
4 |
5 | android {
6 | compileSdkVersion 30
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 30
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | testImplementation 'junit:junit:4.12'
24 | implementation 'androidx.appcompat:appcompat:1.2.0'
25 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
26 | implementation 'com.github.bumptech.glide:glide:4.12.0'
27 | annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
28 | implementation 'com.github.chrisbanes:PhotoView:2.3.0'
29 | }
30 |
31 | //---------------------------------------------
32 |
33 | // 指定编码
34 | tasks.withType(JavaCompile) {
35 | options.encoding = "UTF-8"
36 | }
37 |
38 | // 打包源码
39 | task sourcesJar(type: Jar) {
40 | from android.sourceSets.main.java.srcDirs
41 | classifier = 'sources'
42 | }
43 |
44 | task javadoc(type: Javadoc) {
45 | failOnError false
46 | source = android.sourceSets.main.java.sourceFiles
47 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
48 | classpath += configurations.compile
49 | }
50 |
51 | // 制作文档(Javadoc)
52 | task javadocJar(type: Jar, dependsOn: javadoc) {
53 | classifier = 'javadoc'
54 | from javadoc.destinationDir
55 | }
56 |
57 | artifacts {
58 | archives sourcesJar
59 | archives javadocJar
60 | }
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/DateUtils.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import android.content.Context;
4 |
5 | import com.donkingliang.imageselector.R;
6 |
7 | import java.text.SimpleDateFormat;
8 | import java.util.Calendar;
9 | import java.util.Date;
10 |
11 | public class DateUtils {
12 |
13 | public static String getImageTime(Context context,long time) {
14 | Calendar calendar = Calendar.getInstance();
15 | calendar.setTime(new Date());
16 | Calendar imageTime = Calendar.getInstance();
17 | imageTime.setTimeInMillis(time);
18 | if (sameDay(calendar, imageTime)) {
19 | return context.getString(R.string.selector_this_today);
20 | } else if (sameWeek(calendar, imageTime)) {
21 | return context.getString(R.string.selector_this_week);
22 | } else if (sameMonth(calendar, imageTime)) {
23 | return context.getString(R.string.selector_this_month);
24 | } else {
25 | Date date = new Date(time);
26 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
27 | return sdf.format(date);
28 | }
29 | }
30 |
31 | public static boolean sameDay(Calendar calendar1, Calendar calendar2) {
32 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
33 | && calendar1.get(Calendar.DAY_OF_YEAR) == calendar2.get(Calendar.DAY_OF_YEAR);
34 | }
35 |
36 | public static boolean sameWeek(Calendar calendar1, Calendar calendar2) {
37 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
38 | && calendar1.get(Calendar.WEEK_OF_YEAR) == calendar2.get(Calendar.WEEK_OF_YEAR);
39 | }
40 |
41 | public static boolean sameMonth(Calendar calendar1, Calendar calendar2) {
42 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
43 | && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/java/com/donkingliang/imageselectdemo/adapter/ImageAdapter.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselectdemo.adapter;
2 |
3 | import android.content.Context;
4 | import androidx.recyclerview.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ImageView;
9 |
10 | import com.bumptech.glide.Glide;
11 | import com.donkingliang.imageselectdemo.R;
12 | import com.donkingliang.imageselector.utils.ImageUtil;
13 | import com.donkingliang.imageselector.utils.UriUtils;
14 | import com.donkingliang.imageselector.utils.VersionUtils;
15 |
16 | import java.util.ArrayList;
17 |
18 | public class ImageAdapter extends RecyclerView.Adapter {
19 |
20 | private Context mContext;
21 | private ArrayList mImages;
22 | private LayoutInflater mInflater;
23 | private boolean isAndroidQ = VersionUtils.isAndroidQ();
24 |
25 | public ImageAdapter(Context context) {
26 | mContext = context;
27 | this.mInflater = LayoutInflater.from(mContext);
28 | }
29 |
30 | public ArrayList getImages() {
31 | return mImages;
32 | }
33 |
34 | @Override
35 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
36 | View view = mInflater.inflate(R.layout.adapter_image, parent, false);
37 | return new ViewHolder(view);
38 | }
39 |
40 | @Override
41 | public void onBindViewHolder(final ViewHolder holder, final int position) {
42 | final String image = mImages.get(position);
43 | // 是否是剪切返回的图片
44 | boolean isCutImage = ImageUtil.isCutImage(mContext, image);
45 | if (isAndroidQ && !isCutImage) {
46 | Glide.with(mContext).load(UriUtils.getImageContentUri(mContext, image)).into(holder.ivImage);
47 | } else {
48 | Glide.with(mContext).load(image).into(holder.ivImage);
49 | }
50 |
51 | }
52 |
53 | @Override
54 | public int getItemCount() {
55 | return mImages == null ? 0 : mImages.size();
56 | }
57 |
58 | public void refresh(ArrayList images) {
59 | mImages = images;
60 | notifyDataSetChanged();
61 | }
62 |
63 | static class ViewHolder extends RecyclerView.ViewHolder {
64 |
65 | ImageView ivImage;
66 |
67 | public ViewHolder(View itemView) {
68 | super(itemView);
69 | ivImage = itemView.findViewById(R.id.iv_image);
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
23 |
24 |
32 |
33 |
41 |
42 |
50 |
51 |
59 |
60 |
66 |
67 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/entry/RequestConfig.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.entry;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 |
6 | import java.util.ArrayList;
7 |
8 | /**
9 | * @Author teach liang
10 | * @Description 封装请求参数
11 | * @Date 2019/9/23
12 | */
13 | public class RequestConfig implements Parcelable {
14 |
15 | public boolean isCrop = false; // 是否剪切
16 | public boolean useCamera = true; // 是否支持拍照
17 | public boolean onlyTakePhoto = false; // 仅拍照,不打开相册。true时,useCamera也必定为true。
18 | public boolean isSingle = false; // 是否单选
19 | public boolean canPreview = true; // 是否可以点击图片预览
20 | public int maxSelectCount; //图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。
21 | public ArrayList selected; //接收从外面传进来的已选择的图片列表。当用户原来已经有选择过图片,重新打开选择器,允许用户把先前选过的图片传进来,并把这些图片默认为选中状态。
22 | public float cropRatio = 1.0f; // 图片剪切的宽高比,宽固定为手机屏幕的宽。
23 | public int requestCode;
24 |
25 |
26 | @Override
27 | public int describeContents() {
28 | return 0;
29 | }
30 |
31 | @Override
32 | public void writeToParcel(Parcel dest, int flags) {
33 | dest.writeByte(this.isCrop ? (byte) 1 : (byte) 0);
34 | dest.writeByte(this.useCamera ? (byte) 1 : (byte) 0);
35 | dest.writeByte(this.onlyTakePhoto ? (byte) 1 : (byte) 0);
36 | dest.writeByte(this.isSingle ? (byte) 1 : (byte) 0);
37 | dest.writeByte(this.canPreview ? (byte) 1 : (byte) 0);
38 | dest.writeInt(this.maxSelectCount);
39 | dest.writeStringList(this.selected);
40 | dest.writeFloat(this.cropRatio);
41 | dest.writeInt(this.requestCode);
42 | }
43 |
44 | public RequestConfig() {
45 | }
46 |
47 | protected RequestConfig(Parcel in) {
48 | this.isCrop = in.readByte() != 0;
49 | this.useCamera = in.readByte() != 0;
50 | this.onlyTakePhoto = in.readByte() != 0;
51 | this.isSingle = in.readByte() != 0;
52 | this.canPreview = in.readByte() != 0;
53 | this.maxSelectCount = in.readInt();
54 | this.selected = in.createStringArrayList();
55 | this.cropRatio = in.readFloat();
56 | this.requestCode = in.readInt();
57 | }
58 |
59 | public static final Creator CREATOR = new Creator() {
60 | @Override
61 | public RequestConfig createFromParcel(Parcel source) {
62 | return new RequestConfig(source);
63 | }
64 |
65 | @Override
66 | public RequestConfig[] newArray(int size) {
67 | return new RequestConfig[size];
68 | }
69 | };
70 | }
71 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/adapter_folder.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
15 |
21 |
22 |
23 |
24 |
32 |
33 |
42 |
43 |
50 |
51 |
59 |
60 |
61 |
62 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/entry/Image.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.entry;
2 |
3 | import android.net.Uri;
4 | import android.os.Parcel;
5 | import android.os.Parcelable;
6 |
7 | /**
8 | *图片实体类
9 | */
10 | public class Image implements Parcelable {
11 |
12 | private String path;
13 | private long time;
14 | private String name;
15 | private String mimeType;
16 | private Uri uri;
17 |
18 | public Image(String path, long time, String name, String mimeType, Uri uri) {
19 | this.path = path;
20 | this.time = time;
21 | this.name = name;
22 | this.mimeType = mimeType;
23 | this.uri = uri;
24 | }
25 |
26 | public Uri getUri() {
27 | return uri;
28 | }
29 |
30 | public void setUri(Uri uri) {
31 | this.uri = uri;
32 | }
33 |
34 | public String getPath() {
35 | return path;
36 | }
37 |
38 | public void setPath(String path) {
39 | this.path = path;
40 | }
41 |
42 | public long getTime() {
43 | return time;
44 | }
45 |
46 | public void setTime(long time) {
47 | this.time = time;
48 | }
49 |
50 | public String getName() {
51 | return name;
52 | }
53 |
54 | public void setName(String name) {
55 | this.name = name;
56 | }
57 |
58 | public String getMimeType() {
59 | return mimeType;
60 | }
61 |
62 | public void setMimeType(String mimeType) {
63 | this.mimeType = mimeType;
64 | }
65 |
66 | public boolean isGif(){
67 | return "image/gif".equals(mimeType);
68 | }
69 |
70 |
71 | @Override
72 | public int describeContents() {
73 | return 0;
74 | }
75 |
76 | @Override
77 | public void writeToParcel(Parcel dest, int flags) {
78 | dest.writeString(this.path);
79 | dest.writeLong(this.time);
80 | dest.writeString(this.name);
81 | dest.writeString(this.mimeType);
82 | dest.writeParcelable(this.uri, flags);
83 | }
84 |
85 | protected Image(Parcel in) {
86 | this.path = in.readString();
87 | this.time = in.readLong();
88 | this.name = in.readString();
89 | this.mimeType = in.readString();
90 | this.uri = in.readParcelable(Uri.class.getClassLoader());
91 | }
92 |
93 | public static final Creator CREATOR = new Creator() {
94 | @Override
95 | public Image createFromParcel(Parcel source) {
96 | return new Image(source);
97 | }
98 |
99 | @Override
100 | public Image[] newArray(int size) {
101 | return new Image[size];
102 | }
103 | };
104 | }
105 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/activity_clip_image.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
20 |
21 |
28 |
29 |
30 |
31 |
38 |
39 |
48 |
49 |
57 |
58 |
72 |
73 |
74 |
75 |
76 |
77 |
81 |
82 |
--------------------------------------------------------------------------------
/README1.4.0.md:
--------------------------------------------------------------------------------
1 | # ImageSelector
2 | Android图片选择器,仿微信的图片选择器的样式和效果。支持图片的单选、限数量的多选和不限数量的多选。支持图片预览和图片文件夹的切换。支持图片单选并剪裁。
3 |
4 | 先上效果图:
5 |
6 |   
7 |
8 | **1、引入依赖**
9 |
10 | 在Project的build.gradle在添加以下代码
11 |
12 | ```
13 | allprojects {
14 | repositories {
15 | ...
16 | maven { url 'https://jitpack.io' }
17 | }
18 | }
19 | ```
20 | 在Module的build.gradle在添加以下代码
21 |
22 | ```
23 | compile 'com.github.donkingliang:ImageSelector:1.4.0'
24 | ```
25 |
26 | **2、配置AndroidManifest.xml**
27 | ```xml
28 | //储存卡的读取权限
29 |
30 |
31 | //图片选择Activity
32 |
39 |
40 | //图片预览Activity
41 |
44 |
45 | //图片剪切Activity
46 |
49 | ```
50 | **3、调起图片选择器**
51 |
52 | ImageSelector支持图片的单选、限数量的多选和不限数量的多选。在调起图片选择器的时候需要告诉选择器,是那种情况。为了方便大家的使用,我在项目中提供了一个工具类,可以方便地调起选择器。
53 | 调起选择器只需要简单的一句代码就可以了。
54 | ```java
55 | //单选
56 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, true, 0);
57 |
58 | //限数量的多选(比喻最多9张)
59 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, false, 9);
60 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, false, 9, selected); // 把已选的传入。
61 |
62 | //不限数量的多选
63 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE);
64 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, selected); // 把已选的传入。
65 | //或者
66 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, false, 0);
67 | ImageSelectorUtils.openPhoto(MainActivity.this, REQUEST_CODE, false, 0, selected); // 把已选的传入。
68 |
69 | //单选并剪裁
70 | ImageSelectorUtils.openPhotoAndClip(MainActivity.this, REQUEST_CODE);
71 | ```
72 | REQUEST_CODE就是调用者自己定义的启动Activity时的requestCode,这个相信大家都能明白。selected可以在再次打开选择器时,把原来已经选择过的图片传入,使这些图片默认为选中状态。
73 |
74 | **4、接收选择器返回的数据**
75 |
76 | 在Activity的onActivityResult方法中接收选择器返回的数据。
77 | ```java
78 | @Override
79 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
80 | super.onActivityResult(requestCode, resultCode, data);
81 | if (requestCode == REQUEST_CODE && data != null) {
82 | //获取选择器返回的数据
83 | ArrayList images = data.getStringArrayListExtra(
84 | ImageSelectorUtils.SELECT_RESULT);
85 | }
86 | }
87 | ```
88 | ImageSelectorUtils.SELECT_RESULT是接收数据的key。数据是以ArrayList的字符串数组返回的,就算是单选,返回的也是ArrayList数组,只不过这时候ArrayList只有一条数据而已。ArrayList里面的数据就是选中的图片的文件路径。
89 |
90 | 想要了解ImageSelector的实现思路和核心代码的同学请看这里:[Android 实现一个仿微信的图片选择器](http://blog.csdn.net/u010177022/article/details/70147243)
91 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/adapter/FolderAdapter.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.adapter;
2 |
3 | import android.content.Context;
4 | import androidx.recyclerview.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ImageView;
9 | import android.widget.TextView;
10 |
11 | import com.bumptech.glide.Glide;
12 | import com.bumptech.glide.load.engine.DiskCacheStrategy;
13 | import com.bumptech.glide.request.RequestOptions;
14 | import com.donkingliang.imageselector.R;
15 | import com.donkingliang.imageselector.entry.Folder;
16 | import com.donkingliang.imageselector.entry.Image;
17 | import com.donkingliang.imageselector.utils.VersionUtils;
18 |
19 | import java.util.ArrayList;
20 |
21 | public class FolderAdapter extends RecyclerView.Adapter {
22 |
23 | private Context mContext;
24 | private ArrayList mFolders;
25 | private LayoutInflater mInflater;
26 | private int mSelectItem;
27 | private OnFolderSelectListener mListener;
28 | private boolean isAndroidQ = VersionUtils.isAndroidQ();
29 |
30 | public FolderAdapter(Context context, ArrayList folders) {
31 | mContext = context;
32 | mFolders = folders;
33 | this.mInflater = LayoutInflater.from(context);
34 | }
35 |
36 | @Override
37 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
38 | View view = mInflater.inflate(R.layout.adapter_folder, parent, false);
39 | return new ViewHolder(view);
40 | }
41 |
42 | @Override
43 | public void onBindViewHolder(final ViewHolder holder, int position) {
44 | final Folder folder = mFolders.get(position);
45 | ArrayList images = folder.getImages();
46 | holder.tvFolderName.setText(folder.getName());
47 | holder.ivSelect.setVisibility(mSelectItem == position ? View.VISIBLE : View.GONE);
48 | if (images != null && !images.isEmpty()) {
49 | holder.tvFolderSize.setText(mContext.getString(R.string.selector_image_num,images.size()));
50 | Glide.with(mContext).load(isAndroidQ ? images.get(0).getUri() : images.get(0).getPath())
51 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
52 | .into(holder.ivImage);
53 | } else {
54 | holder.tvFolderSize.setText(mContext.getString(R.string.selector_image_num,0));
55 | holder.ivImage.setImageBitmap(null);
56 | }
57 |
58 | holder.itemView.setOnClickListener(new View.OnClickListener() {
59 | @Override
60 | public void onClick(View v) {
61 | mSelectItem = holder.getAdapterPosition();
62 | notifyDataSetChanged();
63 | if (mListener != null) {
64 | mListener.OnFolderSelect(folder);
65 | }
66 | }
67 | });
68 | }
69 |
70 | @Override
71 | public int getItemCount() {
72 | return mFolders == null ? 0 : mFolders.size();
73 | }
74 |
75 | public void setOnFolderSelectListener(OnFolderSelectListener listener) {
76 | this.mListener = listener;
77 | }
78 |
79 | static class ViewHolder extends RecyclerView.ViewHolder {
80 |
81 | ImageView ivImage;
82 | ImageView ivSelect;
83 | TextView tvFolderName;
84 | TextView tvFolderSize;
85 |
86 | public ViewHolder(View itemView) {
87 | super(itemView);
88 | ivImage = itemView.findViewById(R.id.iv_image);
89 | ivSelect = itemView.findViewById(R.id.iv_select);
90 | tvFolderName = itemView.findViewById(R.id.tv_folder_name);
91 | tvFolderSize = itemView.findViewById(R.id.tv_folder_size);
92 | }
93 | }
94 |
95 | public interface OnFolderSelectListener {
96 | void OnFolderSelect(Folder folder);
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/activity_preview.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
19 |
20 |
25 |
26 |
33 |
34 |
35 |
36 |
43 |
44 |
53 |
54 |
62 |
63 |
77 |
78 |
79 |
80 |
81 |
82 |
89 |
90 |
103 |
104 |
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/adapter/ImagePagerAdapter.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.adapter;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.Matrix;
6 | import androidx.annotation.NonNull;
7 | import androidx.annotation.Nullable;
8 | import androidx.viewpager.widget.PagerAdapter;
9 |
10 | import android.util.Log;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.ImageView;
14 |
15 | import com.bumptech.glide.Glide;
16 | import com.bumptech.glide.load.engine.DiskCacheStrategy;
17 | import com.bumptech.glide.request.RequestOptions;
18 | import com.bumptech.glide.request.target.SimpleTarget;
19 | import com.bumptech.glide.request.transition.Transition;
20 | import com.donkingliang.imageselector.entry.Image;
21 | import com.donkingliang.imageselector.utils.ImageUtil;
22 | import com.donkingliang.imageselector.utils.VersionUtils;
23 | import com.github.chrisbanes.photoview.PhotoView;
24 | import com.github.chrisbanes.photoview.PhotoViewAttacher;
25 |
26 | import java.lang.reflect.Field;
27 | import java.lang.reflect.Method;
28 | import java.util.ArrayList;
29 | import java.util.List;
30 |
31 | public class ImagePagerAdapter extends PagerAdapter {
32 |
33 | private Context mContext;
34 | private List viewList = new ArrayList<>(4);
35 | List mImgList;
36 | private OnItemClickListener mListener;
37 | private boolean isAndroidQ = VersionUtils.isAndroidQ();
38 |
39 | public ImagePagerAdapter(Context context, List imgList) {
40 | this.mContext = context;
41 | createImageViews();
42 | mImgList = imgList;
43 | }
44 |
45 | private void createImageViews() {
46 | for (int i = 0; i < 4; i++) {
47 | PhotoView imageView = new PhotoView(mContext);
48 | imageView.setAdjustViewBounds(true);
49 | viewList.add(imageView);
50 | }
51 | }
52 |
53 | @Override
54 | public int getCount() {
55 | return mImgList == null ? 0 : mImgList.size();
56 | }
57 |
58 | @Override
59 | public boolean isViewFromObject(View view, Object object) {
60 | return view == object;
61 | }
62 |
63 | @Override
64 | public void destroyItem(ViewGroup container, int position, Object object) {
65 | if (object instanceof PhotoView) {
66 | PhotoView view = (PhotoView) object;
67 | view.setImageDrawable(null);
68 | viewList.add(view);
69 | container.removeView(view);
70 | }
71 | }
72 |
73 | @Override
74 | public Object instantiateItem(ViewGroup container, final int position) {
75 | final PhotoView currentView = viewList.remove(0);
76 | final Image image = mImgList.get(position);
77 | container.addView(currentView);
78 | if (image.isGif()) {
79 | currentView.setScaleType(ImageView.ScaleType.FIT_CENTER);
80 | Glide.with(mContext).load(isAndroidQ ? image.getUri() : image.getPath())
81 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)).override(720,1080)
82 | .into(currentView);
83 | } else {
84 | Glide.with(mContext).asBitmap()
85 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
86 | .load(isAndroidQ ? image.getUri() : image.getPath()).into(new SimpleTarget(720,1080) {
87 | @Override
88 | public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition super Bitmap> transition) {
89 | int bw = resource.getWidth();
90 | int bh = resource.getHeight();
91 | if (bw > 4096 || bh > 4096) {
92 | Bitmap bitmap = ImageUtil.zoomBitmap(resource, 4096, 4096);
93 | setBitmap(currentView, bitmap);
94 | } else {
95 | setBitmap(currentView, resource);
96 | }
97 | }
98 | });
99 | }
100 | currentView.setOnClickListener(new View.OnClickListener() {
101 | @Override
102 | public void onClick(View v) {
103 | if (mListener != null) {
104 | mListener.onItemClick(position, image);
105 | }
106 | }
107 | });
108 | return currentView;
109 | }
110 |
111 | private void setBitmap(PhotoView imageView, Bitmap bitmap) {
112 | imageView.setImageBitmap(bitmap);
113 | if (bitmap != null) {
114 | int bw = bitmap.getWidth();
115 | int bh = bitmap.getHeight();
116 | int vw = imageView.getWidth();
117 | int vh = imageView.getHeight();
118 | if (bw != 0 && bh != 0 && vw != 0 && vh != 0) {
119 | if (1.0f * bh / bw > 1.0f * vh / vw) {
120 | imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
121 | float offset = (1.0f * bh * vw / bw - vh) / 2;
122 | adjustOffset(imageView, offset);
123 | } else {
124 | imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
125 | }
126 | }
127 | }
128 | }
129 |
130 | public void setOnItemClickListener(OnItemClickListener l) {
131 | mListener = l;
132 | }
133 |
134 | public interface OnItemClickListener {
135 | void onItemClick(int position, Image image);
136 | }
137 |
138 | private void adjustOffset(PhotoView view, float offset) {
139 | PhotoViewAttacher attacher = view.getAttacher();
140 | try {
141 | Field field = PhotoViewAttacher.class.getDeclaredField("mBaseMatrix");
142 | field.setAccessible(true);
143 | Matrix matrix = (Matrix) field.get(attacher);
144 | matrix.postTranslate(0, offset);
145 | Method method = PhotoViewAttacher.class.getDeclaredMethod("resetMatrix");
146 | method.setAccessible(true);
147 | method.invoke(attacher);
148 | } catch (Exception e) {
149 | e.printStackTrace();
150 | }
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/app/src/main/java/com/donkingliang/imageselectdemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselectdemo;
2 |
3 | import android.Manifest;
4 | import android.content.Intent;
5 | import android.content.pm.PackageManager;
6 | import android.os.Bundle;
7 |
8 | import androidx.appcompat.app.AppCompatActivity;
9 | import androidx.core.app.ActivityCompat;
10 | import androidx.core.content.ContextCompat;
11 | import androidx.recyclerview.widget.GridLayoutManager;
12 | import androidx.recyclerview.widget.RecyclerView;
13 |
14 | import android.view.View;
15 |
16 | import com.donkingliang.imageselectdemo.adapter.ImageAdapter;
17 | import com.donkingliang.imageselector.utils.ImageSelector;
18 |
19 | import java.util.ArrayList;
20 |
21 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
22 |
23 | private static final int REQUEST_CODE = 0x00000011;
24 | private static final int PERMISSION_WRITE_EXTERNAL_REQUEST_CODE = 0x00000012;
25 |
26 | private RecyclerView rvImage;
27 | private ImageAdapter mAdapter;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 |
34 | rvImage = findViewById(R.id.rv_image);
35 | rvImage.setLayoutManager(new GridLayoutManager(this, 3));
36 | mAdapter = new ImageAdapter(this);
37 | rvImage.setAdapter(mAdapter);
38 |
39 | findViewById(R.id.btn_single).setOnClickListener(this);
40 | findViewById(R.id.btn_limit).setOnClickListener(this);
41 | findViewById(R.id.btn_unlimited).setOnClickListener(this);
42 | findViewById(R.id.btn_clip).setOnClickListener(this);
43 | findViewById(R.id.btn_only_take).setOnClickListener(this);
44 | findViewById(R.id.btn_take_and_clip).setOnClickListener(this);
45 |
46 | int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
47 | Manifest.permission.WRITE_EXTERNAL_STORAGE);
48 | if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
49 | //预加载手机图片。加载图片前,请确保app有读取储存卡权限
50 | ImageSelector.preload(this);
51 | } else {
52 | //没有权限,申请权限。
53 | ActivityCompat.requestPermissions(this,
54 | new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
55 | }
56 | }
57 |
58 | @Override
59 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
60 | super.onActivityResult(requestCode, resultCode, data);
61 | if (requestCode == REQUEST_CODE && data != null) {
62 | ArrayList images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
63 | boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
64 | // Log.d("ImageSelector", "是否是拍照图片:" + isCameraImage);
65 | mAdapter.refresh(images);
66 | }
67 | }
68 |
69 | /**
70 | * 处理权限申请的回调。
71 | *
72 | * @param requestCode
73 | * @param permissions
74 | * @param grantResults
75 | */
76 | @Override
77 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
78 | if (requestCode == PERMISSION_WRITE_EXTERNAL_REQUEST_CODE) {
79 | if (grantResults.length > 0
80 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
81 | //预加载手机图片
82 | ImageSelector.preload(this);
83 | } else {
84 | //拒绝权限。
85 | }
86 | }
87 | }
88 |
89 | @Override
90 | public void onClick(View v) {
91 | switch (v.getId()) {
92 | case R.id.btn_single:
93 | //单选
94 | ImageSelector.builder()
95 | .useCamera(true) // 设置是否使用拍照
96 | .setSingle(true) //设置是否单选
97 | .canPreview(true) //是否点击放大图片查看,,默认为true
98 | .start(this, REQUEST_CODE); // 打开相册
99 | break;
100 |
101 | case R.id.btn_limit:
102 | //多选(最多9张)
103 | ImageSelector.builder()
104 | .useCamera(true) // 设置是否使用拍照
105 | .setSingle(false) //设置是否单选
106 | .canPreview(true) //是否点击放大图片查看,,默认为true
107 | .setMaxSelectCount(9) // 图片的最大选择数量,小于等于0时,不限数量。
108 | .start(this, REQUEST_CODE); // 打开相册
109 | break;
110 |
111 | case R.id.btn_unlimited:
112 | //多选(不限数量)
113 | ImageSelector.builder()
114 | .useCamera(true) // 设置是否使用拍照
115 | .setSingle(false) //设置是否单选
116 | .canPreview(true) //是否点击放大图片查看,,默认为true
117 | .setMaxSelectCount(0) // 图片的最大选择数量,小于等于0时,不限数量。
118 | .start(this, REQUEST_CODE); // 打开相册
119 | break;
120 |
121 | case R.id.btn_clip:
122 | //单选并剪裁
123 | ImageSelector.builder()
124 | .useCamera(true) // 设置是否使用拍照
125 | .setCrop(true) // 设置是否使用图片剪切功能。
126 | .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
127 | .setSingle(true) //设置是否单选
128 | .canPreview(true) //是否点击放大图片查看,,默认为true
129 | .start(this, REQUEST_CODE); // 打开相册
130 | break;
131 |
132 | case R.id.btn_only_take:
133 | //仅拍照
134 | ImageSelector.builder()
135 | .onlyTakePhoto(true) // 仅拍照,不打开相册
136 | .start(this, REQUEST_CODE);
137 | break;
138 |
139 | case R.id.btn_take_and_clip:
140 | //拍照并剪裁
141 | ImageSelector.builder()
142 | .setCrop(true) // 设置是否使用图片剪切功能。
143 | .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
144 | .onlyTakePhoto(true) // 仅拍照,不打开相册
145 | .start(this, REQUEST_CODE);
146 | break;
147 | }
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/ClipImageActivity.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.content.pm.ActivityInfo;
6 | import android.graphics.Bitmap;
7 | import android.graphics.Color;
8 | import android.os.Bundle;
9 | import androidx.fragment.app.Fragment;
10 | import android.text.format.DateFormat;
11 | import android.view.View;
12 | import android.view.Window;
13 | import android.view.WindowManager;
14 | import android.widget.FrameLayout;
15 |
16 | import com.donkingliang.imageselector.entry.RequestConfig;
17 | import com.donkingliang.imageselector.utils.ImageSelector;
18 | import com.donkingliang.imageselector.utils.ImageUtil;
19 | import com.donkingliang.imageselector.utils.StringUtils;
20 | import com.donkingliang.imageselector.utils.VersionUtils;
21 | import com.donkingliang.imageselector.view.ClipImageView;
22 |
23 | import java.util.ArrayList;
24 | import java.util.Calendar;
25 | import java.util.Locale;
26 |
27 | public class ClipImageActivity extends Activity {
28 |
29 | private FrameLayout btnConfirm;
30 | private FrameLayout btnBack;
31 | private ClipImageView imageView;
32 | private int mRequestCode;
33 | private boolean isCameraImage;
34 | private float cropRatio;
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
40 | setContentView(R.layout.activity_clip_image);
41 |
42 | Intent intent = getIntent();
43 | RequestConfig config = intent.getParcelableExtra(ImageSelector.KEY_CONFIG);
44 | mRequestCode = config.requestCode;
45 | config.isSingle = true;
46 | config.maxSelectCount = 0;
47 | cropRatio = config.cropRatio;
48 | setStatusBarColor();
49 | ImageSelectorActivity.openActivity(this, mRequestCode, config);
50 | initView();
51 | }
52 |
53 | /**
54 | * 修改状态栏颜色
55 | */
56 | private void setStatusBarColor() {
57 | if (VersionUtils.isAndroidL()) {
58 | Window window = getWindow();
59 | window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
60 | window.setStatusBarColor(Color.parseColor("#373c3d"));
61 | }
62 | }
63 |
64 | private void initView() {
65 | imageView = findViewById(R.id.process_img);
66 | btnConfirm = findViewById(R.id.btn_confirm);
67 | btnBack = findViewById(R.id.btn_back);
68 |
69 | btnConfirm.setOnClickListener(new View.OnClickListener() {
70 | @Override
71 | public void onClick(View v) {
72 | if (imageView.getDrawable() != null) {
73 | btnConfirm.setEnabled(false);
74 | confirm(imageView.clipImage());
75 | }
76 | }
77 | });
78 | btnBack.setOnClickListener(new View.OnClickListener() {
79 | @Override
80 | public void onClick(View v) {
81 | finish();
82 | }
83 | });
84 |
85 | imageView.setRatio(cropRatio);
86 | }
87 |
88 | @Override
89 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
90 | super.onActivityResult(requestCode, resultCode, data);
91 |
92 | if (data != null && requestCode == mRequestCode) {
93 | ArrayList images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
94 | isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
95 | Bitmap bitmap = ImageUtil.decodeSampledBitmapFromFile(this, images.get(0), 720, 1080);
96 | if (bitmap != null) {
97 | imageView.setBitmapData(bitmap);
98 | } else {
99 | finish();
100 | }
101 | } else {
102 | finish();
103 | }
104 | }
105 |
106 | private void confirm(Bitmap bitmap) {
107 | String imagePath = null;
108 | if (bitmap != null) {
109 | String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.getDefault())).toString();
110 | String path = ImageUtil.getImageCacheDir(this);
111 | imagePath = ImageUtil.saveImage(bitmap, path, name);
112 | bitmap.recycle();
113 | bitmap = null;
114 | }
115 |
116 | if (StringUtils.isNotEmptyString(imagePath)) {
117 | ArrayList selectImages = new ArrayList<>();
118 | selectImages.add(imagePath);
119 | Intent intent = new Intent();
120 | intent.putStringArrayListExtra(ImageSelector.SELECT_RESULT, selectImages);
121 | intent.putExtra(ImageSelector.IS_CAMERA_IMAGE, isCameraImage);
122 | setResult(RESULT_OK, intent);
123 | }
124 | finish();
125 | }
126 |
127 | /**
128 | * 启动图片选择器
129 | *
130 | * @param activity
131 | * @param requestCode
132 | * @param config
133 | */
134 | public static void openActivity(Activity activity, int requestCode, RequestConfig config) {
135 | Intent intent = new Intent(activity, ClipImageActivity.class);
136 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
137 | activity.startActivityForResult(intent, requestCode);
138 | }
139 |
140 | /**
141 | * 启动图片选择器
142 | *
143 | * @param fragment
144 | * @param requestCode
145 | * @param config
146 | */
147 | public static void openActivity(Fragment fragment, int requestCode, RequestConfig config) {
148 | Intent intent = new Intent(fragment.getActivity(), ClipImageActivity.class);
149 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
150 | fragment.startActivityForResult(intent, requestCode);
151 | }
152 |
153 | /**
154 | * 启动图片选择器
155 | *
156 | * @param fragment
157 | * @param requestCode
158 | * @param config
159 | */
160 | public static void openActivity(android.app.Fragment fragment, int requestCode, RequestConfig config) {
161 | Intent intent = new Intent(fragment.getActivity(), ClipImageActivity.class);
162 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
163 | fragment.startActivityForResult(intent, requestCode);
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/ImageSelector.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 |
6 | import androidx.fragment.app.Fragment;
7 |
8 | import com.donkingliang.imageselector.ClipImageActivity;
9 | import com.donkingliang.imageselector.ImageSelectorActivity;
10 | import com.donkingliang.imageselector.entry.RequestConfig;
11 | import com.donkingliang.imageselector.model.ImageModel;
12 |
13 | import java.util.ArrayList;
14 |
15 | /**
16 | * Depiction:
17 | * Author:lry
18 | * Date:2018/6/25
19 | */
20 | public class ImageSelector {
21 |
22 | /**
23 | * 图片选择的结果
24 | */
25 | public static final String SELECT_RESULT = "select_result";
26 |
27 | /**
28 | * 是否是来自于相机拍照的图片,
29 | * 只有本次调用相机拍出来的照片,返回时才为true。
30 | * 当为true时,图片返回当结果有且只有一张图片。
31 | */
32 | public static final String IS_CAMERA_IMAGE = "is_camera_image";
33 |
34 | public static final String KEY_CONFIG = "key_config";
35 |
36 | //最大的图片选择数
37 | public static final String MAX_SELECT_COUNT = "max_select_count";
38 | //是否单选
39 | public static final String IS_SINGLE = "is_single";
40 | //初始位置
41 | public static final String POSITION = "position";
42 |
43 | public static final String IS_CONFIRM = "is_confirm";
44 |
45 | public static final int RESULT_CODE = 0x00000012;
46 |
47 | /**
48 | * 预加载图片
49 | *
50 | * @param context
51 | */
52 | public static void preload(Context context) {
53 | ImageModel.preloadAndRegisterContentObserver(context);
54 | }
55 |
56 | /**
57 | * 清空缓存
58 | */
59 | public static void clearCache(Context context) {
60 | ImageModel.clearCache(context);
61 | }
62 |
63 | public static ImageSelectorBuilder builder() {
64 | return new ImageSelectorBuilder();
65 | }
66 |
67 | public static class ImageSelectorBuilder {
68 |
69 | private RequestConfig config;
70 |
71 | private ImageSelectorBuilder() {
72 | config = new RequestConfig();
73 | }
74 |
75 | /**
76 | * 是否使用图片剪切功能。默认false。如果使用了图片剪切功能,相册只能单选。
77 | *
78 | * @param isCrop
79 | * @return
80 | */
81 | public ImageSelectorBuilder setCrop(boolean isCrop) {
82 | config.isCrop = isCrop;
83 | return this;
84 | }
85 |
86 | /**
87 | * 图片剪切的宽高比,宽固定为手机屏幕的宽。
88 | *
89 | * @param ratio
90 | * @return
91 | */
92 | public ImageSelectorBuilder setCropRatio(float ratio) {
93 | config.cropRatio = ratio;
94 | return this;
95 | }
96 |
97 | /**
98 | * 是否单选
99 | *
100 | * @param isSingle
101 | * @return
102 | */
103 | public ImageSelectorBuilder setSingle(boolean isSingle) {
104 | config.isSingle = isSingle;
105 | return this;
106 | }
107 |
108 | /**
109 | * 是否可以点击放大图片查看,默认为true
110 | *
111 | * @param isViewImage
112 | * @return
113 | * @deprecated 请使用canPreview(boolean canPreview);
114 | */
115 | @Deprecated
116 | public ImageSelectorBuilder setViewImage(boolean isViewImage) {
117 | config.canPreview = isViewImage;
118 | return this;
119 | }
120 |
121 | /**
122 | * 是否可以点击预览,默认为true
123 | *
124 | * @param canPreview
125 | * @return
126 | */
127 | public ImageSelectorBuilder canPreview(boolean canPreview) {
128 | config.canPreview = canPreview;
129 | return this;
130 | }
131 |
132 | /**
133 | * 是否使用拍照功能。
134 | *
135 | * @param useCamera 默认为true
136 | * @return
137 | */
138 | public ImageSelectorBuilder useCamera(boolean useCamera) {
139 | config.useCamera = useCamera;
140 | return this;
141 | }
142 |
143 | public ImageSelectorBuilder onlyTakePhoto(boolean onlyTakePhoto) {
144 | config.onlyTakePhoto = onlyTakePhoto;
145 | return this;
146 | }
147 |
148 | /**
149 | * 图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。
150 | *
151 | * @param maxSelectCount
152 | * @return
153 | */
154 | public ImageSelectorBuilder setMaxSelectCount(int maxSelectCount) {
155 | config.maxSelectCount = maxSelectCount;
156 | return this;
157 | }
158 |
159 | /**
160 | * 接收从外面传进来的已选择的图片列表。当用户原来已经有选择过图片,现在重新打开
161 | * 选择器,允许用户把先前选过的图片传进来,并把这些图片默认为选中状态。
162 | *
163 | * @param selected
164 | * @return
165 | */
166 | public ImageSelectorBuilder setSelected(ArrayList selected) {
167 | config.selected = selected;
168 | return this;
169 | }
170 |
171 | /**
172 | * 打开相册
173 | *
174 | * @param activity
175 | * @param requestCode
176 | */
177 | public void start(Activity activity, int requestCode) {
178 | config.requestCode = requestCode;
179 | // 仅拍照,useCamera必须为true
180 | if (config.onlyTakePhoto) {
181 | config.useCamera = true;
182 | }
183 | if (config.isCrop) {
184 | ClipImageActivity.openActivity(activity, requestCode, config);
185 | } else {
186 | ImageSelectorActivity.openActivity(activity, requestCode, config);
187 | }
188 | }
189 |
190 | /**
191 | * 打开相册
192 | *
193 | * @param fragment
194 | * @param requestCode
195 | */
196 | public void start(Fragment fragment, int requestCode) {
197 | config.requestCode = requestCode;
198 | // 仅拍照,useCamera必须为true
199 | if (config.onlyTakePhoto) {
200 | config.useCamera = true;
201 | }
202 | if (config.isCrop) {
203 | ClipImageActivity.openActivity(fragment, requestCode, config);
204 | } else {
205 | ImageSelectorActivity.openActivity(fragment, requestCode, config);
206 | }
207 | }
208 |
209 | /**
210 | * 打开相册
211 | *
212 | * @param fragment
213 | * @param requestCode
214 | */
215 | public void start(android.app.Fragment fragment, int requestCode) {
216 | config.requestCode = requestCode;
217 | // 仅拍照,useCamera必须为true
218 | if (config.onlyTakePhoto) {
219 | config.useCamera = true;
220 | }
221 | if (config.isCrop) {
222 | ClipImageActivity.openActivity(fragment, requestCode, config);
223 | } else {
224 | ImageSelectorActivity.openActivity(fragment, requestCode, config);
225 | }
226 | }
227 | }
228 |
229 | }
230 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/UriUtils.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.ContentUris;
5 | import android.content.ContentValues;
6 | import android.content.Context;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.os.Build;
10 | import android.os.Environment;
11 | import android.provider.DocumentsContract;
12 | import android.provider.MediaStore;
13 | import android.util.Log;
14 |
15 | import java.io.File;
16 |
17 | /**
18 | * @Author teach-梁任彦
19 | * @Description
20 | * @Date 2019-09-11
21 | */
22 | public class UriUtils {
23 |
24 | @SuppressLint("NewApi")
25 | public static String getPathForUri(Context context,Uri uri){
26 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
27 |
28 | // DocumentProvider
29 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
30 | if (isExternalStorageDocument(uri)) {
31 | final String docId = DocumentsContract.getDocumentId(uri);
32 | final String[] split = docId.split(":");
33 | final String type = split[0];
34 |
35 | if ("primary".equalsIgnoreCase(type)) {
36 | if (VersionUtils.isAndroidQ()) {
37 | return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" + split[1];
38 | } else {
39 | return Environment.getExternalStorageDirectory() + "/" + split[1];
40 | }
41 | }
42 | }
43 | // DownloadsProvider
44 | else if (isDownloadsDocument(uri)) {
45 |
46 | final String id = DocumentsContract.getDocumentId(uri);
47 | final Uri contentUri = ContentUris.withAppendedId(
48 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
49 |
50 | return getDataColumn(context, contentUri, null, null);
51 | }
52 | // MediaProvider
53 | else if (isMediaDocument(uri)) {
54 | final String docId = DocumentsContract.getDocumentId(uri);
55 | final String[] split = docId.split(":");
56 | final String type = split[0];
57 |
58 | Uri contentUri = null;
59 | if ("image".equals(type)) {
60 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
61 | } else if ("video".equals(type)) {
62 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
63 | } else if ("audio".equals(type)) {
64 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
65 | }
66 |
67 | final String selection = "_id=?";
68 | final String[] selectionArgs = new String[]{
69 | split[1]
70 | };
71 |
72 | return getDataColumn(context, contentUri, selection, selectionArgs);
73 | }
74 | }
75 | // MediaStore (and general)
76 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
77 |
78 | // Return the remote address
79 | if (isGooglePhotosUri(uri)) {
80 | return uri.getLastPathSegment();
81 | }
82 |
83 | return getDataColumn(context, uri, null, null);
84 | }
85 | // File
86 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
87 | return uri.getPath();
88 | }
89 |
90 | return null;
91 | }
92 |
93 | public static String getDataColumn(Context context, Uri uri, String selection,
94 | String[] selectionArgs) {
95 |
96 | Cursor cursor = null;
97 | final String column = "_data";
98 | final String[] projection = {
99 | column
100 | };
101 |
102 | try {
103 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
104 | null);
105 | if (cursor != null && cursor.moveToFirst()) {
106 | final int column_index = cursor.getColumnIndexOrThrow(column);
107 | return cursor.getString(column_index);
108 | }
109 | } catch (IllegalArgumentException ex) {
110 | } finally {
111 | if (cursor != null) {
112 | cursor.close();
113 | }
114 | }
115 | return null;
116 | }
117 |
118 | /**
119 | * @param uri
120 | * The Uri to check.
121 | * @return Whether the Uri authority is ExternalStorageProvider.
122 | */
123 | private static boolean isExternalStorageDocument(Uri uri) {
124 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
125 | }
126 |
127 | /**
128 | * @param uri
129 | * The Uri to check.
130 | * @return Whether the Uri authority is DownloadsProvider.
131 | */
132 | private static boolean isDownloadsDocument(Uri uri) {
133 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
134 | }
135 |
136 | /**
137 | * @param uri
138 | * The Uri to check.
139 | * @return Whether the Uri authority is MediaProvider.
140 | */
141 | private static boolean isMediaDocument(Uri uri) {
142 | return "com.android.providers.media.documents".equals(uri.getAuthority());
143 | }
144 | /**
145 | * 判断是否是Google相册的图片,类似于content://com.google.android.apps.photos.content/...
146 | **/
147 | public static boolean isGooglePhotosUri(Uri uri) {
148 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
149 | }
150 |
151 | /**
152 | * 判断是否是Google相册的图片,类似于content://com.google.android.apps.photos.contentprovider/0/1/mediakey:/local%3A821abd2f-9f8c-4931-bbe9-a975d1f5fabc/ORIGINAL/NONE/1075342619
153 | **/
154 | public static boolean isGooglePlayPhotosUri(Uri uri) {
155 | return "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority());
156 | }
157 |
158 | /**
159 | * 图片路径转uri
160 | * @param context
161 | * @param path
162 | * @return
163 | */
164 | public static Uri getImageContentUri(Context context, String path) {
165 | Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
166 | new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
167 | new String[] { path }, null);
168 | if (cursor != null && cursor.moveToFirst()) {
169 | int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
170 | Uri baseUri = Uri.parse("content://media/external/images/media");
171 | return Uri.withAppendedPath(baseUri, "" + id);
172 | } else {
173 | if (new File(path).exists()) {
174 | ContentValues values = new ContentValues();
175 | values.put(MediaStore.Images.Media.DATA, path);
176 | return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
177 | } else {
178 | return null;
179 | }
180 | }
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ImageSelector
2 | Android图片选择器,仿微信的图片选择器的样式和效果。支持图片的单选、限数量的多选和不限数量的多选。支持图片预览和图片文件夹的切换。支持在选择图片时调用相机拍照,也支持不用打开相册直接调用相机拍照。
3 |
4 | 先上效果图:
5 |
6 |   
7 |
8 | **1、引入依赖**
9 |
10 | 在Project的build.gradle在添加以下代码
11 |
12 | ```
13 | allprojects {
14 | repositories {
15 | ...
16 | maven { url 'https://jitpack.io' }
17 | }
18 | }
19 | ```
20 | 在Module的build.gradle在添加以下代码
21 |
22 | ```
23 | implementation 'com.github.donkingliang:ImageSelector:2.2.1'
24 | ```
25 | 从2.0.0版本开始,库迁移androidx。没有使用androidx的项目可以使用1.9.3版本。
26 |
27 | **2、配置AndroidManifest.xml**
28 |
29 | ***注意:*** 1.7.0版本后,不需要再配置FileProvider,ImageSelector内部已经配置了。
30 | ```xml
31 | //储存卡的读写权限
32 |
33 |
34 | //调用相机权限
35 |
36 |
37 | //图片选择Activity
38 |
45 |
46 | //图片预览Activity
47 |
50 |
51 | //图片剪切Activity
52 |
55 |
56 |
57 |
62 |
65 |
66 | ```
67 | 在res/xml文件夹下创建file_paths.xml文件(名字可以自己定义)
68 |
69 | ```xml
70 |
71 |
72 |
73 |
74 |
77 |
78 | ```
79 |
80 | **3、调起图片选择器**
81 |
82 | ImageSelector支持图片的单选、限数量的多选和不限数量的多选。还可以设置是否使用相机、是否剪切图片等配置。ImageSelector提供了统一的调起相册的方法。
83 | ```java
84 | //单选
85 | ImageSelector.builder()
86 | .useCamera(true) // 设置是否使用拍照
87 | .setSingle(true) //设置是否单选
88 | .canPreview(true) //是否可以预览图片,默认为true
89 | .start(this, REQUEST_CODE); // 打开相册
90 |
91 | //限数量的多选(比如最多9张)
92 | ImageSelector.builder()
93 | .useCamera(true) // 设置是否使用拍照
94 | .setSingle(false) //设置是否单选
95 | .setMaxSelectCount(9) // 图片的最大选择数量,小于等于0时,不限数量。
96 | .setSelected(selected) // 把已选的图片传入默认选中。
97 | .canPreview(true) //是否可以预览图片,默认为true
98 | .start(this, REQUEST_CODE); // 打开相册
99 |
100 | //不限数量的多选
101 | ImageSelector.builder()
102 | .useCamera(true) // 设置是否使用拍照
103 | .setSingle(false) //设置是否单选
104 | .setMaxSelectCount(0) // 图片的最大选择数量,小于等于0时,不限数量。
105 | .setSelected(selected) // 把已选的图片传入默认选中。
106 | .canPreview(true) //是否可以预览图片,默认为true
107 | .start(this, REQUEST_CODE); // 打开相册
108 |
109 | //单选并剪裁
110 | ImageSelector.builder()
111 | .useCamera(true) // 设置是否使用拍照
112 | .setCrop(true) // 设置是否使用图片剪切功能。
113 | .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
114 | .setSingle(true) //设置是否单选
115 | .canPreview(true) //是否可以预览图片,默认为true
116 | .start(this, REQUEST_CODE); // 打开相册
117 |
118 | //仅拍照
119 | ImageSelector.builder()
120 | .onlyTakePhoto(true) // 仅拍照,不打开相册
121 | .start(this, REQUEST_CODE);
122 |
123 | //拍照并剪裁
124 | ImageSelector.builder()
125 | .setCrop(true) // 设置是否使用图片剪切功能。
126 | .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
127 | .onlyTakePhoto(true) // 仅拍照,不打开相册
128 | .start(this, REQUEST_CODE);
129 |
130 | ```
131 | REQUEST_CODE就是调用者自己定义的启动Activity时的requestCode,这个相信大家都能明白。selected可以在再次打开选择器时,把原来已经选择过的图片传入,使这些图片默认为选中状态。
132 |
133 | 如果是仅拍照模式(onlyTakePhoto = true)时,useCamera无论设置什么,都是为true。
134 |
135 | **4、接收选择器返回的数据**
136 |
137 | 在Activity的onActivityResult方法中接收选择器返回的数据。
138 | ```java
139 | @Override
140 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
141 | super.onActivityResult(requestCode, resultCode, data);
142 | if (requestCode == REQUEST_CODE && data != null) {
143 | //获取选择器返回的数据
144 | ArrayList images = data.getStringArrayListExtra(
145 | ImageSelector.SELECT_RESULT);
146 |
147 | /**
148 | * 是否是来自于相机拍照的图片,
149 | * 只有本次调用相机拍出来的照片,返回时才为true。
150 | * 当为true时,图片返回的结果有且只有一张图片。
151 | */
152 | boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
153 | }
154 | }
155 | ```
156 | ImageSelector.SELECT_RESULT是接收数据的key。数据是以ArrayList的字符串数组返回的,就算是单选,返回的也是ArrayList数组,只不过这时候ArrayList只有一条数据而已。ArrayList里面的数据就是选中的图片的文件路径。
157 |
158 | **适配android 10**
159 |
160 | 兼容android 10的手机请使用1.7.0版本。
161 |
162 | 由于android 10不允许应用直接访问外部文件,所以在android 10及以上的手机,ImageSelect返回的图片链接可能无法直接加载,因为ImageSelector返回的是图片在手机里的地址。但是可以通过uri进行加载,ImageSelector内部提供了一些方法可以供外部使用,用于适配android 10。
163 |
164 | 如何在Android 10加载手机本地图片,请看我的[这篇博客](https://juejin.im/post/5d80ef726fb9a06aeb10f223)。
165 | ```
166 | //是否是android 10及以上
167 | VersionUtils.isAndroidQ();
168 |
169 | // android 10可以通过图片uri加载手机本地图片。
170 |
171 | //图片链接转uri
172 | Uri uri = UriUtils.getImageContentUri(Context context, String path);
173 |
174 | //通过uri加载图片
175 | Glide.with(mContext).load(uri).into(ivImage);
176 | ivImage.setImageURI(uri);
177 | // 或者
178 | Bitmap bitmap = ImageUtil.getBitmapFromUri(Context context, Uri uri);
179 | ```
180 |
181 | ***注意:*** 剪切返回的图片的图片链接是放在应用的私有目录的,所以剪切返回的图片可以直接用path加载,不需要转成uri再加载。ImageSelector提供了判断图片链接是否是剪切的图片的方法。
182 | ```
183 | // 是否是剪切返回的图片
184 | ImageUtil.isCutImage(mContext, path);
185 | ```
186 |
187 | **图片预加载和缓存**
188 |
189 | 由于从手机中加载图库是个耗时操作,图片太多时,打开图库可能等待时间过长,用户体验不好。所以在2.1.0版本和1.9.0版本开始,提供了预加载手机图片并缓存的功能。你可以在用户打开图片选择器前,预先加载手机图片,这样在用户打开图片选择器时,会直接从缓存中读取图片列表,大大提升选择器的加载速度。
190 |
191 | 选择器默认不开启预加载并缓存功能,如果需要预加载,请调用下面的方法:
192 | ```java
193 | ImageSelector.preload(context);
194 | ```
195 | 调用这个方法的时机没有特殊的要求,只要是在打开选择器前调用就可以了。
196 |
197 | ***注意:*** 由于加载手机图片需要申请WRITE_EXTERNAL_STORAGE权限,所以在调用该方法前,请确保权限已申请。
198 |
199 | 在选择器使用完毕,不再需要时,可以调用下面方法清空缓存:
200 | ```java
201 | ImageSelector.clearCache(context);
202 | ```
203 | 清空缓存的操作不是必须的,如果不清空,缓存会一直保留,直到app被回收。因为缓存的是图片的路径,所以不会占用太多的内存。
204 |
205 | **版本节点**
206 |
207 | 这里记录的是重要的版本更新节点,全部的版本及更新内容请看[这里](https://github.com/donkingliang/ImageSelector/releases)。
208 |
209 | ***2.1.0版本&1.9.0版本***
210 |
211 | 添加图片预加载和缓存功能。
212 |
213 | ***2.0.0版本***
214 |
215 | 迁移androidx。没有使用androidx的项目可以使用1.9.2版本。
216 |
217 | ***1.8.0版本***
218 |
219 | 1、添加直接打开相机拍照功能。
220 |
221 | 2、优化图片预览页,适配刘海屏。
222 |
223 | ***1.7.0版本***
224 |
225 | 1、适配android 10。
226 |
227 | 2、添加自定义FileProvider,从1.7.0开始,使用者不需要再配置FileProvider。
228 |
229 | ***1.5.0版本***
230 |
231 | 1、更新Glide版本到4.x。
232 |
233 | 2、修改targetSdkVersion为27。
234 |
235 | ImageSelector从1.5.0版本开始使用了Glide 4.x的版本,由于Glide 3.x版本和4.x版本在使用上有所差异,如果你的项目使用了Glide 3.x版本,而又不想升级到4.x,那么你也可以使用ImageSelector:1.4.0版本,它和新的版本在使用和功能上都会有所差异。[ImageSelector 1.4.0](https://github.com/donkingliang/ImageSelector/blob/master/README1.4.0.md)
236 |
237 | 想要了解ImageSelector的实现思路和核心代码的同学请看这里:[Android 实现一个仿微信的图片选择器](https://juejin.im/post/5919086244d904006c692abb)
238 |
--------------------------------------------------------------------------------
/imageselector/src/main/res/layout/activity_image_select.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
18 |
19 |
26 |
27 |
28 |
29 |
36 |
37 |
46 |
47 |
55 |
56 |
70 |
71 |
72 |
73 |
74 |
75 |
86 |
87 |
99 |
100 |
108 |
109 |
122 |
123 |
129 |
130 |
136 |
137 |
143 |
144 |
150 |
151 |
158 |
159 |
160 |
161 |
162 |
163 |
169 |
170 |
181 |
182 |
183 |
184 |
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/adapter/ImageAdapter.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.adapter;
2 |
3 | import android.content.Context;
4 | import androidx.recyclerview.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ImageView;
9 |
10 | import com.bumptech.glide.Glide;
11 | import com.bumptech.glide.load.engine.DiskCacheStrategy;
12 | import com.bumptech.glide.request.RequestOptions;
13 | import com.donkingliang.imageselector.R;
14 | import com.donkingliang.imageselector.entry.Image;
15 | import com.donkingliang.imageselector.utils.VersionUtils;
16 |
17 | import java.util.ArrayList;
18 |
19 | public class ImageAdapter extends RecyclerView.Adapter {
20 |
21 | private Context mContext;
22 | private ArrayList mImages;
23 | private LayoutInflater mInflater;
24 |
25 | //保存选中的图片
26 | private ArrayList mSelectImages = new ArrayList<>();
27 | private OnImageSelectListener mSelectListener;
28 | private OnItemClickListener mItemClickListener;
29 | private int mMaxCount;
30 | private boolean isSingle;
31 | private boolean isViewImage;
32 |
33 | private static final int TYPE_CAMERA = 1;
34 | private static final int TYPE_IMAGE = 2;
35 |
36 | private boolean useCamera;
37 |
38 | private boolean isAndroidQ = VersionUtils.isAndroidQ();
39 |
40 | /**
41 | * @param maxCount 图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。
42 | * @param isSingle 是否单选
43 | * @param isViewImage 是否点击放大图片查看
44 | */
45 | public ImageAdapter(Context context, int maxCount, boolean isSingle, boolean isViewImage) {
46 | mContext = context;
47 | this.mInflater = LayoutInflater.from(mContext);
48 | mMaxCount = maxCount;
49 | this.isSingle = isSingle;
50 | this.isViewImage = isViewImage;
51 | }
52 |
53 | @Override
54 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
55 | if (viewType == TYPE_IMAGE) {
56 | View view = mInflater.inflate(R.layout.adapter_images_item, parent, false);
57 | return new ViewHolder(view);
58 | } else {
59 | View view = mInflater.inflate(R.layout.adapter_camera, parent, false);
60 | return new ViewHolder(view);
61 | }
62 | }
63 |
64 | @Override
65 | public void onBindViewHolder(final ViewHolder holder, int position) {
66 | if (getItemViewType(position) == TYPE_IMAGE) {
67 | final Image image = getImage(position);
68 | Glide.with(mContext).load(isAndroidQ ? image.getUri() : image.getPath())
69 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
70 | .into(holder.ivImage);
71 |
72 | setItemSelect(holder, mSelectImages.contains(image));
73 |
74 | holder.ivGif.setVisibility(image.isGif() ? View.VISIBLE : View.GONE);
75 |
76 | //点击选中/取消选中图片
77 | holder.ivSelectIcon.setOnClickListener(new View.OnClickListener() {
78 | @Override
79 | public void onClick(View v) {
80 | checkedImage(holder, image);
81 | }
82 | });
83 |
84 | holder.itemView.setOnClickListener(new View.OnClickListener() {
85 | @Override
86 | public void onClick(View v) {
87 | if (isViewImage) {
88 | if (mItemClickListener != null) {
89 | int p = holder.getAdapterPosition();
90 | mItemClickListener.OnItemClick(image, useCamera ? p - 1 : p);
91 | }
92 | } else {
93 | checkedImage(holder, image);
94 | }
95 | }
96 | });
97 | } else if (getItemViewType(position) == TYPE_CAMERA) {
98 | holder.itemView.setOnClickListener(new View.OnClickListener() {
99 | @Override
100 | public void onClick(View v) {
101 | if (mItemClickListener != null) {
102 | mItemClickListener.OnCameraClick();
103 | }
104 | }
105 | });
106 | }
107 | }
108 |
109 | @Override
110 | public int getItemViewType(int position) {
111 | if (useCamera && position == 0) {
112 | return TYPE_CAMERA;
113 | } else {
114 | return TYPE_IMAGE;
115 | }
116 | }
117 |
118 | private void checkedImage(ViewHolder holder, Image image) {
119 | if (mSelectImages.contains(image)) {
120 | //如果图片已经选中,就取消选中
121 | unSelectImage(image);
122 | setItemSelect(holder, false);
123 | } else if (isSingle) {
124 | //如果是单选,就先清空已经选中的图片,再选中当前图片
125 | clearImageSelect();
126 | selectImage(image);
127 | setItemSelect(holder, true);
128 | } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) {
129 | //如果不限制图片的选中数量,或者图片的选中数量
130 | // 还没有达到最大限制,就直接选中当前图片。
131 | selectImage(image);
132 | setItemSelect(holder, true);
133 | }
134 | }
135 |
136 | /**
137 | * 选中图片
138 | *
139 | * @param image
140 | */
141 | private void selectImage(Image image) {
142 | mSelectImages.add(image);
143 | if (mSelectListener != null) {
144 | mSelectListener.OnImageSelect(image, true, mSelectImages.size());
145 | }
146 | }
147 |
148 | /**
149 | * 取消选中图片
150 | *
151 | * @param image
152 | */
153 | private void unSelectImage(Image image) {
154 | mSelectImages.remove(image);
155 | if (mSelectListener != null) {
156 | mSelectListener.OnImageSelect(image, false, mSelectImages.size());
157 | }
158 | }
159 |
160 |
161 | @Override
162 | public int getItemCount() {
163 | return useCamera ? getImageCount() + 1 : getImageCount();
164 | }
165 |
166 | private int getImageCount() {
167 | return mImages == null ? 0 : mImages.size();
168 | }
169 |
170 | public ArrayList getData() {
171 | return mImages;
172 | }
173 |
174 | public void refresh(ArrayList data, boolean useCamera) {
175 | mImages = data;
176 | this.useCamera = useCamera;
177 | notifyDataSetChanged();
178 | }
179 |
180 | private Image getImage(int position) {
181 | return mImages.get(useCamera ? position - 1 : position);
182 | }
183 |
184 | public Image getFirstVisibleImage(int firstVisibleItem) {
185 | if (mImages != null && !mImages.isEmpty()) {
186 | if (useCamera) {
187 | return mImages.get(firstVisibleItem > 0 ? firstVisibleItem - 1 : 0);
188 | } else {
189 | return mImages.get(firstVisibleItem < 0 ? 0 : firstVisibleItem);
190 | }
191 | }
192 | return null;
193 | }
194 |
195 | /**
196 | * 设置图片选中和未选中的效果
197 | */
198 | private void setItemSelect(ViewHolder holder, boolean isSelect) {
199 | if (isSelect) {
200 | holder.ivSelectIcon.setImageResource(R.drawable.icon_image_select);
201 | holder.ivMasking.setAlpha(0.5f);
202 | } else {
203 | holder.ivSelectIcon.setImageResource(R.drawable.icon_image_un_select);
204 | holder.ivMasking.setAlpha(0.2f);
205 | }
206 | }
207 |
208 | private void clearImageSelect() {
209 | if (mImages != null && mSelectImages.size() == 1) {
210 | int index = mImages.indexOf(mSelectImages.get(0));
211 | mSelectImages.clear();
212 | if (index != -1) {
213 | notifyItemChanged(useCamera ? index + 1 : index);
214 | }
215 | }
216 | }
217 |
218 | public void setSelectedImages(ArrayList selected) {
219 | if (mImages != null && selected != null) {
220 | for (String path : selected) {
221 | if (isFull()) {
222 | return;
223 | }
224 | for (Image image : mImages) {
225 | if (path.equals(image.getPath())) {
226 | if (!mSelectImages.contains(image)) {
227 | mSelectImages.add(image);
228 | }
229 | break;
230 | }
231 | }
232 | }
233 | notifyDataSetChanged();
234 | }
235 | }
236 |
237 |
238 | private boolean isFull() {
239 | if (isSingle && mSelectImages.size() == 1) {
240 | return true;
241 | } else if (mMaxCount > 0 && mSelectImages.size() == mMaxCount) {
242 | return true;
243 | } else {
244 | return false;
245 | }
246 | }
247 |
248 | public ArrayList getSelectImages() {
249 | return mSelectImages;
250 | }
251 |
252 | public void setOnImageSelectListener(OnImageSelectListener listener) {
253 | this.mSelectListener = listener;
254 | }
255 |
256 | public void setOnItemClickListener(OnItemClickListener listener) {
257 | this.mItemClickListener = listener;
258 | }
259 |
260 | static class ViewHolder extends RecyclerView.ViewHolder {
261 |
262 | ImageView ivImage;
263 | ImageView ivSelectIcon;
264 | ImageView ivMasking;
265 | ImageView ivGif;
266 | ImageView ivCamera;
267 |
268 | public ViewHolder(View itemView) {
269 | super(itemView);
270 | ivImage = itemView.findViewById(R.id.iv_image);
271 | ivSelectIcon = itemView.findViewById(R.id.iv_select);
272 | ivMasking = itemView.findViewById(R.id.iv_masking);
273 | ivGif = itemView.findViewById(R.id.iv_gif);
274 |
275 | ivCamera = itemView.findViewById(R.id.iv_camera);
276 | }
277 | }
278 |
279 | public interface OnImageSelectListener {
280 | void OnImageSelect(Image image, boolean isSelect, int selectCount);
281 | }
282 |
283 | public interface OnItemClickListener {
284 | void OnItemClick(Image image, int position);
285 |
286 | void OnCameraClick();
287 | }
288 | }
289 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/model/ImageModel.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.model;
2 |
3 | import android.Manifest;
4 | import android.content.ContentResolver;
5 | import android.content.Context;
6 | import android.content.pm.PackageManager;
7 | import android.database.ContentObserver;
8 | import android.database.Cursor;
9 | import android.net.Uri;
10 | import android.provider.MediaStore;
11 |
12 | import com.donkingliang.imageselector.R;
13 | import com.donkingliang.imageselector.entry.Folder;
14 | import com.donkingliang.imageselector.entry.Image;
15 | import com.donkingliang.imageselector.utils.ImageUtil;
16 | import com.donkingliang.imageselector.utils.StringUtils;
17 | import com.donkingliang.imageselector.utils.UriUtils;
18 |
19 | import java.io.File;
20 | import java.util.ArrayList;
21 | import java.util.Collections;
22 | import java.util.Comparator;
23 | import java.util.List;
24 |
25 | import androidx.core.content.ContextCompat;
26 |
27 | public class ImageModel {
28 |
29 | /**
30 | * 缓存图片
31 | */
32 | private static ArrayList cacheImageList = null;
33 | private static boolean isNeedCache = false;
34 | private static PhotoContentObserver observer;
35 |
36 | /**
37 | * 预加载图片
38 | *
39 | * @param context
40 | */
41 | public static void preloadAndRegisterContentObserver(final Context context) {
42 | isNeedCache = true;
43 | if (observer == null) {
44 | observer = new PhotoContentObserver(context.getApplicationContext());
45 | context.getApplicationContext().getContentResolver().registerContentObserver(
46 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, observer);
47 | }
48 | preload(context);
49 | }
50 |
51 | private static void preload(final Context context) {
52 | int hasWriteExternalPermission = ContextCompat.checkSelfPermission(context,
53 | Manifest.permission.WRITE_EXTERNAL_STORAGE);
54 | if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
55 | //有权限,加载图片。
56 | loadImageForSDCard(context, true, null);
57 | }
58 | }
59 |
60 | /**
61 | * 清空缓存
62 | */
63 | public static void clearCache(Context context) {
64 | isNeedCache = false;
65 | if (observer != null) {
66 | context.getApplicationContext().getContentResolver().unregisterContentObserver(observer);
67 | observer = null;
68 | }
69 | new Thread(new Runnable() {
70 | @Override
71 | public void run() {
72 | synchronized (ImageModel.class) {
73 | if (cacheImageList != null) {
74 | cacheImageList.clear();
75 | cacheImageList = null;
76 | }
77 | }
78 | }
79 | }).start();
80 | }
81 |
82 | /**
83 | * 从SDCard加载图片
84 | *
85 | * @param context
86 | * @param callback
87 | */
88 | public static void loadImageForSDCard(final Context context, final DataCallback callback) {
89 | loadImageForSDCard(context, false, callback);
90 | }
91 |
92 | /**
93 | * 从SDCard加载图片
94 | *
95 | * @param context
96 | * @param isPreload 是否是预加载
97 | * @param callback
98 | */
99 | private static void loadImageForSDCard(final Context context, final boolean isPreload, final DataCallback callback) {
100 | //由于扫描图片是耗时的操作,所以要在子线程处理。
101 | new Thread(new Runnable() {
102 | @Override
103 | public void run() {
104 | synchronized (ImageModel.class) {
105 | String imageCacheDir = ImageUtil.getImageCacheDir(context);
106 | ArrayList folders = null;
107 | if (cacheImageList == null || isPreload) {
108 | ArrayList imageList = loadImage(context);
109 | Collections.sort(imageList, new Comparator() {
110 | @Override
111 | public int compare(Image image, Image t1) {
112 | if (image.getTime() > t1.getTime()) {
113 | return 1;
114 | } else if (image.getTime() < t1.getTime()) {
115 | return -1;
116 | } else {
117 | return 0;
118 | }
119 | }
120 | });
121 | ArrayList images = new ArrayList<>();
122 |
123 | for (Image image : imageList) {
124 | // 过滤不存在或未下载完成的图片
125 | boolean exists = !"downloading".equals(getExtensionName(image.getPath())) && checkImgExists(image.getPath());
126 | //过滤剪切保存的图片;
127 | boolean isCutImage = ImageUtil.isCutImage(imageCacheDir, image.getPath());
128 | if (!isCutImage && exists) {
129 | images.add(image);
130 | }
131 | }
132 | Collections.reverse(images);
133 | folders = splitFolder(context, images);
134 | if (isNeedCache) {
135 | cacheImageList = folders;
136 | }
137 | } else {
138 | folders = cacheImageList;
139 | }
140 |
141 | if (callback != null) {
142 | callback.onSuccess(folders);
143 | }
144 | }
145 | }
146 | }).start();
147 | }
148 |
149 | /**
150 | * 从SDCard加载图片
151 | *
152 | * @param context
153 | * @return
154 | */
155 | private static synchronized ArrayList loadImage(Context context) {
156 |
157 | //扫描图片
158 | Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
159 | ContentResolver mContentResolver = context.getContentResolver();
160 |
161 | Cursor mCursor = mContentResolver.query(mImageUri, new String[]{
162 | MediaStore.Images.Media.DATA,
163 | MediaStore.Images.Media.DISPLAY_NAME,
164 | MediaStore.Images.Media.DATE_ADDED,
165 | MediaStore.Images.Media._ID,
166 | MediaStore.Images.Media.MIME_TYPE,
167 | MediaStore.Images.Media.SIZE},
168 | MediaStore.MediaColumns.SIZE + ">0",
169 | null,
170 | MediaStore.Images.Media.DATE_ADDED + " DESC");
171 |
172 | ArrayList images = new ArrayList<>();
173 |
174 | //读取扫描到的图片
175 | if (mCursor != null) {
176 | while (mCursor.moveToNext()) {
177 | // 获取图片的路径
178 | long id = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
179 | String path = mCursor.getString(
180 | mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
181 | //获取图片名称
182 | String name = mCursor.getString(
183 | mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
184 | //获取图片时间
185 | long time = mCursor.getLong(
186 | mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
187 |
188 | if (String.valueOf(time).length() < 13) {
189 | time *= 1000;
190 | }
191 |
192 | //获取图片类型
193 | String mimeType = mCursor.getString(
194 | mCursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE));
195 |
196 | //获取图片uri
197 | Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon()
198 | .appendPath(String.valueOf(id)).build();
199 |
200 | images.add(new Image(path, time, name, mimeType, uri));
201 | }
202 | mCursor.close();
203 | }
204 | return images;
205 | }
206 |
207 | /**
208 | * 检查图片是否存在。ContentResolver查询处理的数据有可能文件路径并不存在。
209 | *
210 | * @param filePath
211 | * @return
212 | */
213 | private static boolean checkImgExists(String filePath) {
214 | return new File(filePath).exists();
215 | }
216 |
217 | private static String getPathForAndroidQ(Context context, long id) {
218 | return UriUtils.getPathForUri(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon()
219 | .appendPath(String.valueOf(id)).build());
220 | }
221 |
222 | /**
223 | * 把图片按文件夹拆分,第一个文件夹保存所有的图片
224 | *
225 | * @param images
226 | * @return
227 | */
228 | private static ArrayList splitFolder(Context context, ArrayList images) {
229 | ArrayList folders = new ArrayList<>();
230 | folders.add(new Folder(context.getString(R.string.selector_all_image), images));
231 |
232 | if (images != null && !images.isEmpty()) {
233 | int size = images.size();
234 | for (int i = 0; i < size; i++) {
235 | String path = images.get(i).getPath();
236 | String name = getFolderName(path);
237 | if (StringUtils.isNotEmptyString(name)) {
238 | Folder folder = getFolder(name, folders);
239 | folder.addImage(images.get(i));
240 | }
241 | }
242 | }
243 | return folders;
244 | }
245 |
246 | /**
247 | * Java文件操作 获取文件扩展名
248 | */
249 | public static String getExtensionName(String filename) {
250 | if (filename != null && filename.length() > 0) {
251 | int dot = filename.lastIndexOf('.');
252 | if (dot > -1 && dot < filename.length() - 1) {
253 | return filename.substring(dot + 1);
254 | }
255 | }
256 | return "";
257 | }
258 |
259 | /**
260 | * 根据图片路径,获取图片文件夹名称
261 | *
262 | * @param path
263 | * @return
264 | */
265 | private static String getFolderName(String path) {
266 | if (StringUtils.isNotEmptyString(path)) {
267 | String[] strings = path.split(File.separator);
268 | if (strings.length >= 2) {
269 | return strings[strings.length - 2];
270 | }
271 | }
272 | return "";
273 | }
274 |
275 | private static Folder getFolder(String name, List folders) {
276 | if (!folders.isEmpty()) {
277 | int size = folders.size();
278 | for (int i = 0; i < size; i++) {
279 | Folder folder = folders.get(i);
280 | if (name.equals(folder.getName())) {
281 | return folder;
282 | }
283 | }
284 | }
285 | Folder newFolder = new Folder(name);
286 | folders.add(newFolder);
287 | return newFolder;
288 | }
289 |
290 | public interface DataCallback {
291 | void onSuccess(ArrayList folders);
292 | }
293 |
294 | private static class PhotoContentObserver extends ContentObserver {
295 |
296 | private Context context;
297 |
298 | public PhotoContentObserver(Context appContext) {
299 | super(null);
300 | context = appContext;
301 | }
302 |
303 | @Override
304 | public void onChange(boolean selfChange, Uri uri) {
305 | super.onChange(selfChange, uri);
306 | preload(context);
307 | }
308 | }
309 | }
310 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/view/ClipImageView.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.view;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.Canvas;
6 | import android.graphics.Color;
7 | import android.graphics.Matrix;
8 | import android.graphics.Paint;
9 | import android.graphics.PointF;
10 | import android.graphics.PorterDuff;
11 | import android.graphics.PorterDuffXfermode;
12 | import android.graphics.Rect;
13 | import android.graphics.RectF;
14 | import android.graphics.Xfermode;
15 |
16 | import androidx.appcompat.widget.AppCompatImageView;
17 |
18 | import android.util.AttributeSet;
19 | import android.util.DisplayMetrics;
20 | import android.util.Log;
21 | import android.view.MotionEvent;
22 | import android.view.WindowManager;
23 |
24 | public class ClipImageView extends AppCompatImageView {
25 |
26 | private PointF mDownPoint;
27 | private PointF mMiddlePoint;
28 | private Matrix mMatrix;
29 | private Matrix mTempMatrix;
30 |
31 | private int mBitmapWidth;
32 | private int mBitmapHeight;
33 |
34 | private final int MODE_NONE = 0;
35 | private final int MODE_DRAG = 1;
36 | private final int MODE_ZOOM = 2;
37 | private final int MODE_POINTER_UP = 3;
38 | private int CURR_MODE = MODE_NONE;
39 |
40 | private float mLastDistance;
41 |
42 | private Paint mFrontGroundPaint = new Paint();
43 | private int mTargetWidth;
44 | private int mTargetHeight;
45 | private Xfermode mXfermode;
46 | private Rect r;
47 | private RectF rf;
48 |
49 | private float mCircleCenterX, mCircleCenterY;
50 | private float mCircleX, mCircleY;
51 | private boolean isCutImage;
52 | private float mRatio = 1.0f;
53 |
54 | public ClipImageView(Context context) {
55 | super(context);
56 | setRadius();
57 | }
58 |
59 | public ClipImageView(Context context, AttributeSet attrs) {
60 | super(context, attrs);
61 | setRadius();
62 | }
63 |
64 | /**
65 | * 设置要剪裁的图片
66 | *
67 | * @param bitmap
68 | */
69 | public void setBitmapData(Bitmap bitmap) {
70 |
71 | if (bitmap == null) {
72 | return;
73 | }
74 |
75 | mBitmapHeight = bitmap.getHeight();
76 | mBitmapWidth = bitmap.getWidth();
77 | setImageBitmap(bitmap);
78 | init();
79 | }
80 |
81 | private void init() {
82 | mDownPoint = new PointF();
83 | mMiddlePoint = new PointF();
84 | mMatrix = new Matrix();
85 | mTempMatrix = new Matrix();
86 | mFrontGroundPaint.setColor(Color.parseColor("#ac000000"));
87 | mFrontGroundPaint.setAntiAlias(true);
88 | mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
89 |
90 | setScaleType(ScaleType.MATRIX);
91 | post(new Runnable() {
92 | @Override
93 | public void run() {
94 | center();
95 | }
96 | });
97 | }
98 |
99 | @Override
100 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
101 | super.onLayout(changed, left, top, right, bottom);
102 | setRadius();
103 | }
104 |
105 | private void setRadius() {
106 | mTargetWidth = getScreenWidth(getContext());
107 | mTargetHeight = (int) (mTargetWidth * mRatio);
108 | mCircleCenterX = getWidth() / 2;
109 | mCircleCenterY = getHeight() / 2;
110 | mCircleX = mCircleCenterX - mTargetWidth / 2;
111 | mCircleY = mCircleCenterY - mTargetHeight / 2;
112 | }
113 |
114 | public void setRatio(float ratio) {
115 | if (mRatio != ratio) {
116 | mRatio = ratio;
117 | setRadius();
118 | invalidate();
119 | }
120 | }
121 |
122 | @Override
123 | protected void onDraw(Canvas canvas) {
124 | super.onDraw(canvas);
125 | if (isCutImage) {
126 | return;
127 | }
128 | if (rf == null || rf.isEmpty()) {
129 | r = new Rect(0, 0, getWidth(), getHeight());
130 | rf = new RectF(r);
131 | }
132 | // 画入前景圆形蒙板层
133 | int sc = canvas.saveLayer(rf, null, Canvas.ALL_SAVE_FLAG);
134 | //画入矩形黑色半透明蒙板层
135 | canvas.drawRect(r, mFrontGroundPaint);
136 | //设置Xfermode,目的是为了去除矩形黑色半透明蒙板层和圆形的相交部分
137 | mFrontGroundPaint.setXfermode(mXfermode);
138 | //画入正方形
139 | float left = mCircleCenterX - mTargetWidth / 2;
140 | float top = mCircleCenterY - mTargetHeight / 2;
141 | float right = mCircleCenterX + mTargetWidth / 2;
142 | float bottom = mCircleCenterY + mTargetHeight / 2;
143 | canvas.drawRect(left, top, right, bottom, mFrontGroundPaint);
144 |
145 | canvas.restoreToCount(sc);
146 | //清除Xfermode,防止影响下次画图
147 | mFrontGroundPaint.setXfermode(null);
148 | }
149 |
150 | /**
151 | * 截取Bitmap
152 | *
153 | * @return
154 | */
155 | public Bitmap clipImage() {
156 | isCutImage = true;
157 | Paint paint = new Paint();
158 | setDrawingCacheEnabled(true);
159 | Bitmap bitmap = getDrawingCache();
160 | Bitmap targetBitmap = Bitmap.createBitmap(mTargetWidth, mTargetHeight,
161 | Bitmap.Config.ARGB_8888);
162 | Canvas canvas = new Canvas(targetBitmap);
163 | int left = -bitmap.getWidth() / 2 + mTargetWidth / 2;
164 | int top = -getHeight() / 2 + mTargetHeight / 2;
165 | int right = bitmap.getWidth() / 2 + mTargetWidth / 2;
166 | int bottom = getHeight() / 2 + mTargetHeight / 2;
167 | RectF dst = new RectF(left, top, right, bottom);
168 | canvas.drawBitmap(bitmap, null, dst, paint);
169 | setDrawingCacheEnabled(false);
170 | bitmap.recycle();
171 | bitmap = null;
172 | isCutImage = false;
173 | //返回正方形图片
174 | return targetBitmap;
175 | }
176 |
177 | @Override
178 | public boolean onTouchEvent(MotionEvent event) {
179 |
180 | if (mMatrix == null) {
181 | return super.onTouchEvent(event);
182 | }
183 |
184 | float[] values = new float[9];
185 | mMatrix.getValues(values);
186 | float left = values[Matrix.MTRANS_X];
187 | float top = values[Matrix.MTRANS_Y];
188 | float right = (left + mBitmapWidth * values[Matrix.MSCALE_X]);
189 | float bottom = (top + mBitmapHeight * values[Matrix.MSCALE_Y]);
190 | float x = 0f;
191 | float y = 0f;
192 |
193 | switch (event.getAction() & MotionEvent.ACTION_MASK) {
194 |
195 | case MotionEvent.ACTION_DOWN:
196 | CURR_MODE = MODE_DRAG;
197 | mDownPoint.set(event.getX(), event.getY());
198 | break;
199 | case MotionEvent.ACTION_POINTER_DOWN:
200 | if (getDistance(event) > 10f) {
201 | CURR_MODE = MODE_ZOOM;
202 | midPoint(mMiddlePoint, event);
203 | mLastDistance = getDistance(event);
204 | }
205 | break;
206 | case MotionEvent.ACTION_MOVE:
207 | //如果当前模式为拖曳(单指触屏)
208 | if (CURR_MODE == MODE_DRAG || CURR_MODE == MODE_POINTER_UP) {
209 | if (CURR_MODE == MODE_DRAG) {
210 |
211 | x = event.getX() - mDownPoint.x;
212 | y = event.getY() - mDownPoint.y;
213 | //left靠边
214 | if (x + left > mCircleX) {
215 | x = 0;
216 | }
217 | //right靠边
218 | if (x + right < mCircleX + mTargetWidth) {
219 | x = 0;
220 | }
221 | //top靠边
222 | if (y + top > mCircleY) {
223 | y = 0;
224 | }
225 | //bottom靠边
226 | if (y + bottom < mCircleY + mTargetHeight) {
227 | y = 0;
228 | }
229 | mMatrix.postTranslate(x, y);
230 | mDownPoint.set(event.getX(), event.getY());
231 |
232 | } else {
233 | CURR_MODE = MODE_DRAG;
234 | mDownPoint.set(event.getX(), event.getY());
235 | }
236 | } else {
237 | //否则当前模式为缩放(双指触屏)
238 | float distance = getDistance(event);
239 | if (distance > 10f) {
240 | float scale = distance / mLastDistance;
241 |
242 | //left靠边
243 | if (left >= mCircleX) {
244 | mMiddlePoint.x = 0;
245 | }
246 | //right靠边
247 | if (right <= mCircleX + mTargetWidth) {
248 | mMiddlePoint.x = right;
249 | }
250 | //top靠边
251 | if (top >= mCircleY) {
252 | mMiddlePoint.y = 0;
253 | }
254 | //bottom靠边
255 | if (bottom <= mCircleY + mTargetHeight) {
256 | mMiddlePoint.y = bottom;
257 | }
258 | mTempMatrix.set(mMatrix);
259 | mTempMatrix.postScale(scale, scale, mMiddlePoint.x, mMiddlePoint.y);
260 |
261 | float[] temp_values = new float[9];
262 | mTempMatrix.getValues(temp_values);
263 | float temp_left = temp_values[Matrix.MTRANS_X];
264 | float temp_top = temp_values[Matrix.MTRANS_Y];
265 | float temp_right = (temp_left + mBitmapWidth * temp_values[Matrix.MSCALE_X]);
266 | float temp_bottom = (temp_top + mBitmapHeight * temp_values[Matrix.MSCALE_Y]);
267 | //靠边预判断
268 | if (temp_left > mCircleX || temp_right < mCircleX + mTargetWidth ||
269 | temp_top > mCircleY || temp_bottom < mCircleY + mTargetHeight) {
270 | return true;
271 | }
272 | mMatrix.postScale(scale, scale, mMiddlePoint.x, mMiddlePoint.y);
273 | mLastDistance = getDistance(event);
274 | }
275 | }
276 | break;
277 | case MotionEvent.ACTION_UP:
278 | CURR_MODE = MODE_NONE;
279 | break;
280 | case MotionEvent.ACTION_POINTER_UP:
281 | CURR_MODE = MODE_POINTER_UP;
282 | break;
283 | }
284 | setImageMatrix(mMatrix);
285 | return true;
286 | }
287 |
288 |
289 | /**
290 | * 两点的距离
291 | */
292 | private float getDistance(MotionEvent event) {
293 | float x = event.getX(0) - event.getX(1);
294 | float y = event.getY(0) - event.getY(1);
295 | return (float) Math.sqrt(x * x + y * y);
296 | }
297 |
298 | /**
299 | * 两点的中点
300 | */
301 | private void midPoint(PointF point, MotionEvent event) {
302 | float x = event.getX(0) + event.getX(1);
303 | float y = event.getY(0) + event.getY(1);
304 | point.set(x / 2, y / 2);
305 | }
306 |
307 | /**
308 | * 横向、纵向居中
309 | */
310 | protected void center() {
311 | float height = mBitmapHeight;
312 | float width = mBitmapWidth;
313 | float scale = Math.max(mTargetWidth / width,mTargetHeight / height);
314 |
315 | float deltaX = -(width * scale - getWidth()) / 2.0f;
316 | float deltaY = -(height * scale - getHeight()) / 2.0f;
317 | mMatrix.postScale(scale, scale);
318 | mMatrix.postTranslate(deltaX, deltaY);
319 | setImageMatrix(mMatrix);
320 | }
321 |
322 | /**
323 | * 获得屏幕宽度
324 | */
325 | public static int getScreenWidth(Context context) {
326 | WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
327 | DisplayMetrics outMetrics = new DisplayMetrics();
328 | wm.getDefaultDisplay().getMetrics(outMetrics);
329 | return outMetrics.widthPixels;
330 | }
331 |
332 | /**
333 | * 获得屏幕高度
334 | */
335 | public static int getScreenHeight(Context context) {
336 | WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
337 | DisplayMetrics outMetrics = new DisplayMetrics();
338 | wm.getDefaultDisplay().getMetrics(outMetrics);
339 | return outMetrics.heightPixels;
340 | }
341 | }
342 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/utils/ImageUtil.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector.utils;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.ContentResolver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.database.Cursor;
8 | import android.graphics.Bitmap;
9 | import android.graphics.BitmapFactory;
10 | import android.graphics.Matrix;
11 | import android.media.ExifInterface;
12 | import android.net.Uri;
13 | import android.os.Environment;
14 | import android.os.ParcelFileDescriptor;
15 | import android.provider.MediaStore;
16 | import android.util.Log;
17 |
18 | import java.io.File;
19 | import java.io.FileDescriptor;
20 | import java.io.FileNotFoundException;
21 | import java.io.FileOutputStream;
22 | import java.io.IOException;
23 |
24 | public class ImageUtil {
25 |
26 | /**
27 | * 获取缓存图片的文件夹
28 | *
29 | * @param context
30 | * @return
31 | */
32 | public static String getImageCacheDir(Context context) {
33 | File file = null;
34 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
35 | || !Environment.isExternalStorageRemovable()) {
36 | if (VersionUtils.isAndroidQ()) {
37 | file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
38 | } else {
39 | file = context.getExternalCacheDir();
40 | }
41 | }
42 |
43 | if (file == null) {
44 | file = context.getCacheDir();
45 | }
46 | return file.getPath() + File.separator + "image_select";
47 | }
48 |
49 | /**
50 | * 保存图片
51 | *
52 | * @param bitmap
53 | * @param path
54 | * @param name
55 | * @return
56 | */
57 | public static String saveImage(Bitmap bitmap, String path, String name) {
58 | FileOutputStream b = null;
59 | File file = new File(path);
60 | if (!file.exists()) {
61 | file.mkdirs();// 创建文件夹
62 | }
63 |
64 | String fileName = path + File.separator + name + ".jpg";
65 |
66 | try {
67 | b = new FileOutputStream(fileName);
68 | bitmap.compress(Bitmap.CompressFormat.JPEG, 75, b);// 把数据写入文件
69 | return fileName;
70 | } catch (FileNotFoundException e) {
71 | e.printStackTrace();
72 | } finally {
73 | try {
74 | if (b != null) {
75 | b.flush();
76 | b.close();
77 | }
78 | } catch (IOException e) {
79 | e.printStackTrace();
80 | }
81 | }
82 | return "";
83 | }
84 |
85 | public static Bitmap zoomBitmap(Bitmap bm, int reqWidth, int reqHeight) {
86 | // 获得图片的宽高
87 | int width = bm.getWidth();
88 | int height = bm.getHeight();
89 | // 计算缩放比例
90 | float scaleWidth = ((float) reqWidth) / width;
91 | float scaleHeight = ((float) reqHeight) / height;
92 | float scale = Math.min(scaleWidth, scaleHeight);
93 | // 取得想要缩放的matrix参数
94 | Matrix matrix = new Matrix();
95 | matrix.postScale(scale, scale);
96 | // 得到新的图片
97 | Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
98 | true);
99 | return newbm;
100 | }
101 |
102 | /**
103 | * 根据计算的inSampleSize,得到压缩后图片
104 | *
105 | * @param pathName
106 | * @param reqWidth
107 | * @param reqHeight
108 | * @return
109 | */
110 | @SuppressLint("NewApi")
111 | public static Bitmap decodeSampledBitmapFromFile(Context context, String pathName, int reqWidth, int reqHeight) {
112 |
113 | int degree = 0;
114 |
115 | Uri uri = UriUtils.getImageContentUri(context, pathName);
116 | ParcelFileDescriptor parcelFileDescriptor = null;
117 | FileDescriptor fileDescriptor = null;
118 | try {
119 |
120 | parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
121 | fileDescriptor = parcelFileDescriptor.getFileDescriptor();
122 |
123 | ExifInterface exifInterface = null;
124 | if (VersionUtils.isAndroidQ()) {
125 | exifInterface = new ExifInterface(fileDescriptor);
126 | } else {
127 | exifInterface = new ExifInterface(pathName);
128 | }
129 |
130 | int result = exifInterface.getAttributeInt(
131 | ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
132 | switch (result) {
133 | case ExifInterface.ORIENTATION_ROTATE_90:
134 | degree = 90;
135 | break;
136 | case ExifInterface.ORIENTATION_ROTATE_180:
137 | degree = 180;
138 | break;
139 | case ExifInterface.ORIENTATION_ROTATE_270:
140 | degree = 270;
141 | break;
142 | }
143 | } catch (IOException e) {
144 | e.printStackTrace();
145 | return null;
146 | }
147 |
148 | try {
149 |
150 | // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
151 | final BitmapFactory.Options options = new BitmapFactory.Options();
152 | options.inJustDecodeBounds = true;
153 | if (VersionUtils.isAndroidQ()) {
154 | BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
155 | } else {
156 | BitmapFactory.decodeFile(pathName, options);
157 | }
158 | // 调用上面定义的方法计算inSampleSize值
159 | options.inSampleSize = calculateInSampleSize(options, reqWidth,
160 | reqHeight);
161 |
162 | // 使用获取到的inSampleSize值再次解析图片
163 | options.inJustDecodeBounds = false;
164 | // options.inPreferredConfig = Bitmap.Config.RGB_565;
165 |
166 | Bitmap bitmap = null;
167 | if (VersionUtils.isAndroidQ()) {
168 | bitmap = getBitmapFromUri(context, uri, options);
169 | } else {
170 | bitmap = BitmapFactory.decodeFile(pathName, options);
171 | }
172 |
173 | parcelFileDescriptor.close();
174 |
175 | if (degree != 0) {
176 | Bitmap newBitmap = rotateImageView(bitmap, degree);
177 | bitmap.recycle();
178 | bitmap = null;
179 | return newBitmap;
180 | }
181 |
182 | return bitmap;
183 | } catch (OutOfMemoryError error) {
184 | Log.e("eee", "内存泄露!");
185 | } catch (IOException e) {
186 | e.printStackTrace();
187 | }
188 | return null;
189 | }
190 |
191 | /**
192 | * 获取Bitmap
193 | *
194 | * @param context
195 | * @param uri
196 | * @return
197 | */
198 | public static Bitmap getBitmapFromUri(Context context, Uri uri) {
199 | return getBitmapFromUri(context, uri, null);
200 | }
201 |
202 | /**
203 | * 获取Bitmap
204 | *
205 | * @param context
206 | * @param uri
207 | * @return
208 | */
209 | public static Bitmap getBitmapFromUri(Context context, Uri uri, BitmapFactory.Options options) {
210 | try {
211 | ParcelFileDescriptor parcelFileDescriptor =
212 | context.getContentResolver().openFileDescriptor(uri, "r");
213 | FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
214 | Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
215 | parcelFileDescriptor.close();
216 | return image;
217 | } catch (Exception e) {
218 | e.printStackTrace();
219 | }
220 | return null;
221 | }
222 |
223 | /**
224 | * 旋转图片
225 | *
226 | * @param bitmap
227 | * @param angle
228 | * @return Bitmap
229 | */
230 | public static Bitmap rotateImageView(Bitmap bitmap, int angle) {
231 | //旋转图片 动作
232 | Matrix matrix = new Matrix();
233 | matrix.postRotate(angle);
234 | // 创建新的图片
235 | return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
236 | }
237 |
238 | /**
239 | * 计算inSampleSize,用于压缩图片
240 | *
241 | * @param options
242 | * @param reqWidth
243 | * @param reqHeight
244 | * @return
245 | */
246 | private static int calculateInSampleSize(BitmapFactory.Options options,
247 | int reqWidth, int reqHeight) {
248 | // 源图片的宽度
249 | int width = options.outWidth;
250 | int height = options.outHeight;
251 | int inSampleSize = 1;
252 |
253 | if (width > reqWidth && height > reqHeight) {
254 | // 计算出实际宽度和目标宽度的比率
255 | int widthRatio = Math.round((float) width / (float) reqWidth);
256 | int heightRatio = Math.round((float) height / (float) reqHeight);
257 | inSampleSize = Math.max(widthRatio, heightRatio);
258 | }
259 |
260 | return inSampleSize;
261 | }
262 |
263 | public static boolean isEffective(String path) {
264 | final BitmapFactory.Options options = new BitmapFactory.Options();
265 | options.inJustDecodeBounds = true;
266 | BitmapFactory.decodeFile(path, options);
267 | return options.outWidth > 0 && options.outHeight > 0;
268 | }
269 |
270 | public static boolean isEffective(Context context, Uri uri) {
271 | try {
272 | ParcelFileDescriptor parcelFileDescriptor =
273 | context.getContentResolver().openFileDescriptor(uri, "r");
274 | FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
275 | final BitmapFactory.Options options = new BitmapFactory.Options();
276 | options.inJustDecodeBounds = true;
277 | BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
278 | return options.outWidth > 0 && options.outHeight > 0;
279 | } catch (IOException e) {
280 | e.printStackTrace();
281 | }
282 | return false;
283 | }
284 |
285 | /**
286 | * 是否是剪切返回的图片
287 | *
288 | * @param context
289 | * @param path
290 | * @return
291 | */
292 | public static boolean isCutImage(Context context, String path) {
293 | return isCutImage(getImageCacheDir(context), path);
294 | }
295 |
296 | /**
297 | * 是否是剪切返回的图片
298 | *
299 | * @param dir
300 | * @param path
301 | * @return
302 | */
303 | public static boolean isCutImage(String dir, String path) {
304 | if (!StringUtils.isEmptyString(path)) {
305 | return path.startsWith(dir);
306 | }
307 | return false;
308 | }
309 |
310 | /**
311 | * 保存拍照的图片
312 | *
313 | * @param context
314 | * @param uri
315 | * @param takeTime 调起相机拍照的时间
316 | */
317 | public static void savePicture(final Context context, final Uri uri, final long takeTime) {
318 | new Thread(new Runnable() {
319 | @Override
320 | public void run() {
321 | if (isNeedSavePicture(context, takeTime)) {
322 | context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
323 | }
324 | }
325 | }).start();
326 | }
327 |
328 | /**
329 | * 是否需要保存拍照的图片
330 | *
331 | * @param context
332 | * @return
333 | */
334 | private static boolean isNeedSavePicture(Context context, long takeTime) {
335 | //扫描图片
336 | Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
337 | .buildUpon().appendQueryParameter("limit","1").build();
338 | ContentResolver mContentResolver = context.getContentResolver();
339 | Cursor mCursor = mContentResolver.query(mImageUri, new String[]{
340 | MediaStore.Images.Media.DATE_ADDED,
341 | MediaStore.Images.Media._ID,
342 | MediaStore.Images.Media.SIZE},
343 | MediaStore.MediaColumns.SIZE + ">0",
344 | null,
345 | MediaStore.Files.FileColumns._ID + " DESC");
346 |
347 | //读取扫描到的图片
348 | if (mCursor != null && mCursor.getCount() > 0 && mCursor.moveToFirst()) {
349 | //获取图片时间
350 | long time = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
351 | int id = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
352 | if (String.valueOf(time).length() < 13) {
353 | time *= 1000;
354 | }
355 | mCursor.close();
356 |
357 | // 如果照片的插入时间大于相机的拍照时间,就认为是拍照图片已插入
358 | return time + 1000 < takeTime;
359 | }
360 | return true;
361 | }
362 | }
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/PreviewActivity.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector;
2 |
3 | import android.animation.Animator;
4 | import android.animation.AnimatorListenerAdapter;
5 | import android.animation.ObjectAnimator;
6 | import android.app.Activity;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.res.Resources;
10 | import android.graphics.Bitmap;
11 | import android.graphics.BitmapFactory;
12 | import android.graphics.Color;
13 | import android.graphics.drawable.BitmapDrawable;
14 | import android.os.Build;
15 | import android.os.Bundle;
16 | import androidx.annotation.Nullable;
17 | import androidx.viewpager.widget.ViewPager;
18 | import androidx.appcompat.app.AppCompatActivity;
19 | import android.view.View;
20 | import android.view.Window;
21 | import android.view.WindowManager;
22 | import android.widget.FrameLayout;
23 | import android.widget.RelativeLayout;
24 | import android.widget.TextView;
25 |
26 | import com.donkingliang.imageselector.adapter.ImagePagerAdapter;
27 | import com.donkingliang.imageselector.entry.Image;
28 | import com.donkingliang.imageselector.utils.ImageSelector;
29 | import com.donkingliang.imageselector.utils.VersionUtils;
30 | import com.donkingliang.imageselector.view.MyViewPager;
31 |
32 | import java.util.ArrayList;
33 |
34 | import static android.animation.ObjectAnimator.ofFloat;
35 |
36 | public class PreviewActivity extends AppCompatActivity {
37 |
38 | private MyViewPager vpImage;
39 | private TextView tvIndicator;
40 | private TextView tvConfirm;
41 | private FrameLayout btnConfirm;
42 | private TextView tvSelect;
43 | private RelativeLayout rlTopBar;
44 | private RelativeLayout rlBottomBar;
45 |
46 | //tempImages和tempSelectImages用于图片列表数据的页面传输。
47 | //之所以不要Intent传输这两个图片列表,因为要保证两位页面操作的是同一个列表数据,同时可以避免数据量大时,
48 | // 用Intent传输发生的错误问题。
49 | private static ArrayList tempImages;
50 | private static ArrayList tempSelectImages;
51 |
52 | private ArrayList mImages;
53 | private ArrayList mSelectImages;
54 | private boolean isShowBar = true;
55 | private boolean isConfirm = false;
56 | private boolean isSingle;
57 | private int mMaxCount;
58 |
59 | private BitmapDrawable mSelectDrawable;
60 | private BitmapDrawable mUnSelectDrawable;
61 |
62 | public static void openActivity(Activity activity, ArrayList images,
63 | ArrayList selectImages, boolean isSingle,
64 | int maxSelectCount, int position) {
65 | tempImages = images;
66 | tempSelectImages = selectImages;
67 | Intent intent = new Intent(activity, PreviewActivity.class);
68 | intent.putExtra(ImageSelector.MAX_SELECT_COUNT, maxSelectCount);
69 | intent.putExtra(ImageSelector.IS_SINGLE, isSingle);
70 | intent.putExtra(ImageSelector.POSITION, position);
71 | activity.startActivityForResult(intent, ImageSelector.RESULT_CODE);
72 | }
73 |
74 | @Override
75 | protected void onCreate(@Nullable Bundle savedInstanceState) {
76 | super.onCreate(savedInstanceState);
77 | setContentView(R.layout.activity_preview);
78 |
79 | if (VersionUtils.isAndroidP()) {
80 | //设置页面全屏显示
81 | WindowManager.LayoutParams lp = getWindow().getAttributes();
82 | lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
83 | //设置页面延伸到刘海区显示
84 | getWindow().setAttributes(lp);
85 | }
86 |
87 | setStatusBarVisible(true);
88 | mImages = tempImages;
89 | tempImages = null;
90 | mSelectImages = tempSelectImages;
91 | tempSelectImages = null;
92 |
93 | Intent intent = getIntent();
94 | mMaxCount = intent.getIntExtra(ImageSelector.MAX_SELECT_COUNT, 0);
95 | isSingle = intent.getBooleanExtra(ImageSelector.IS_SINGLE, false);
96 |
97 | Resources resources = getResources();
98 | Bitmap selectBitmap = BitmapFactory.decodeResource(resources, R.drawable.icon_image_select);
99 | mSelectDrawable = new BitmapDrawable(resources, selectBitmap);
100 | mSelectDrawable.setBounds(0, 0, selectBitmap.getWidth(), selectBitmap.getHeight());
101 |
102 | Bitmap unSelectBitmap = BitmapFactory.decodeResource(resources, R.drawable.icon_image_un_select);
103 | mUnSelectDrawable = new BitmapDrawable(resources, unSelectBitmap);
104 | mUnSelectDrawable.setBounds(0, 0, unSelectBitmap.getWidth(), unSelectBitmap.getHeight());
105 |
106 | setStatusBarColor();
107 | initView();
108 | initListener();
109 | initViewPager();
110 |
111 | tvIndicator.setText(1 + "/" + mImages.size());
112 | changeSelect(mImages.get(0));
113 | vpImage.setCurrentItem(intent.getIntExtra(ImageSelector.POSITION, 0));
114 | }
115 |
116 | private void initView() {
117 | vpImage = findViewById(R.id.vp_image);
118 | tvIndicator = findViewById(R.id.tv_indicator);
119 | tvConfirm = findViewById(R.id.tv_confirm);
120 | btnConfirm = findViewById(R.id.btn_confirm);
121 | tvSelect = findViewById(R.id.tv_select);
122 | rlTopBar = findViewById(R.id.rl_top_bar);
123 | rlBottomBar = findViewById(R.id.rl_bottom_bar);
124 |
125 | RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) rlTopBar.getLayoutParams();
126 | lp.topMargin = getStatusBarHeight(this);
127 | rlTopBar.setLayoutParams(lp);
128 | }
129 |
130 | private void initListener() {
131 | findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
132 | @Override
133 | public void onClick(View v) {
134 | finish();
135 | }
136 | });
137 | btnConfirm.setOnClickListener(new View.OnClickListener() {
138 | @Override
139 | public void onClick(View v) {
140 | isConfirm = true;
141 | finish();
142 | }
143 | });
144 | tvSelect.setOnClickListener(new View.OnClickListener() {
145 | @Override
146 | public void onClick(View v) {
147 | clickSelect();
148 | }
149 | });
150 | }
151 |
152 | /**
153 | * 初始化ViewPager
154 | */
155 | private void initViewPager() {
156 | ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages);
157 | vpImage.setAdapter(adapter);
158 | adapter.setOnItemClickListener(new ImagePagerAdapter.OnItemClickListener() {
159 | @Override
160 | public void onItemClick(int position, Image image) {
161 | if (isShowBar) {
162 | hideBar();
163 | } else {
164 | showBar();
165 | }
166 | }
167 | });
168 | vpImage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
169 | @Override
170 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
171 | }
172 |
173 | @Override
174 | public void onPageSelected(int position) {
175 | tvIndicator.setText(position + 1 + "/" + mImages.size());
176 | changeSelect(mImages.get(position));
177 | }
178 |
179 | @Override
180 | public void onPageScrollStateChanged(int state) {
181 | }
182 | });
183 | }
184 |
185 | /**
186 | * 修改状态栏颜色
187 | */
188 | private void setStatusBarColor() {
189 | if (VersionUtils.isAndroidL()) {
190 | Window window = getWindow();
191 | window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
192 | window.setStatusBarColor(Color.parseColor("#373c3d"));
193 | }
194 | }
195 |
196 | /**
197 | * 获取状态栏高度
198 | *
199 | * @param context
200 | * @return
201 | */
202 | public static int getStatusBarHeight(Context context) {
203 | int result = 0;
204 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
205 | if (resourceId > 0) {
206 | result = context.getResources().getDimensionPixelSize(resourceId);
207 | }
208 | return result;
209 | }
210 |
211 | /**
212 | * 显示和隐藏状态栏
213 | *
214 | * @param show
215 | */
216 | private void setStatusBarVisible(boolean show) {
217 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
218 | if (show) {
219 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
220 | } else {
221 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
222 | | View.SYSTEM_UI_FLAG_FULLSCREEN);
223 |
224 | }
225 | }
226 | }
227 |
228 | /**
229 | * 显示头部和尾部栏
230 | */
231 | private void showBar() {
232 | isShowBar = true;
233 | setStatusBarVisible(true);
234 | //添加延时,保证StatusBar完全显示后再进行动画。
235 | rlTopBar.postDelayed(new Runnable() {
236 | @Override
237 | public void run() {
238 | if (rlTopBar != null) {
239 | ObjectAnimator animator = ofFloat(rlTopBar, "translationY",
240 | rlTopBar.getTranslationY(), 0).setDuration(300);
241 | animator.addListener(new AnimatorListenerAdapter() {
242 | @Override
243 | public void onAnimationStart(Animator animation) {
244 | super.onAnimationStart(animation);
245 | if (rlTopBar != null) {
246 | rlTopBar.setVisibility(View.VISIBLE);
247 | }
248 | }
249 | });
250 | animator.start();
251 | ofFloat(rlBottomBar, "translationY", rlBottomBar.getTranslationY(), 0)
252 | .setDuration(300).start();
253 | }
254 | }
255 | }, 100);
256 | }
257 |
258 | /**
259 | * 隐藏头部和尾部栏
260 | */
261 | private void hideBar() {
262 | isShowBar = false;
263 | ObjectAnimator animator = ObjectAnimator.ofFloat(rlTopBar, "translationY",
264 | 0, -rlTopBar.getHeight()).setDuration(300);
265 | animator.addListener(new AnimatorListenerAdapter() {
266 | @Override
267 | public void onAnimationEnd(Animator animation) {
268 | super.onAnimationEnd(animation);
269 | if (rlTopBar != null) {
270 | rlTopBar.setVisibility(View.GONE);
271 | //添加延时,保证rlTopBar完全隐藏后再隐藏StatusBar。
272 | rlTopBar.postDelayed(new Runnable() {
273 | @Override
274 | public void run() {
275 | setStatusBarVisible(false);
276 | }
277 | }, 5);
278 | }
279 | }
280 | });
281 | animator.start();
282 | ofFloat(rlBottomBar, "translationY", 0, rlBottomBar.getHeight())
283 | .setDuration(300).start();
284 | }
285 |
286 | private void clickSelect() {
287 | int position = vpImage.getCurrentItem();
288 | if (mImages != null && mImages.size() > position) {
289 | Image image = mImages.get(position);
290 | if (mSelectImages.contains(image)) {
291 | mSelectImages.remove(image);
292 | } else if (isSingle) {
293 | mSelectImages.clear();
294 | mSelectImages.add(image);
295 | } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) {
296 | mSelectImages.add(image);
297 | }
298 | changeSelect(image);
299 | }
300 | }
301 |
302 | private void changeSelect(Image image) {
303 | tvSelect.setCompoundDrawables(mSelectImages.contains(image) ?
304 | mSelectDrawable : mUnSelectDrawable, null, null, null);
305 | setSelectImageCount(mSelectImages.size());
306 | }
307 |
308 | private void setSelectImageCount(int count) {
309 | if (count == 0) {
310 | btnConfirm.setEnabled(false);
311 | tvConfirm.setText(R.string.selector_send);
312 | } else {
313 | btnConfirm.setEnabled(true);
314 | if (isSingle) {
315 | tvConfirm.setText(R.string.selector_send);
316 | } else if (mMaxCount > 0) {
317 | tvConfirm.setText(getString(R.string.selector_send) + "(" + count + "/" + mMaxCount + ")");
318 | } else {
319 | tvConfirm.setText(getString(R.string.selector_send) + "(" + count + ")");
320 | }
321 | }
322 | }
323 |
324 | @Override
325 | public void finish() {
326 | //Activity关闭时,通过Intent把用户的操作(确定/返回)传给ImageSelectActivity。
327 | Intent intent = new Intent();
328 | intent.putExtra(ImageSelector.IS_CONFIRM, isConfirm);
329 | setResult(ImageSelector.RESULT_CODE, intent);
330 | super.finish();
331 | }
332 | }
333 |
--------------------------------------------------------------------------------
/imageselector/src/main/java/com/donkingliang/imageselector/ImageSelectorActivity.java:
--------------------------------------------------------------------------------
1 | package com.donkingliang.imageselector;
2 |
3 | import android.Manifest;
4 | import android.animation.Animator;
5 | import android.animation.AnimatorListenerAdapter;
6 | import android.animation.ObjectAnimator;
7 | import android.app.Activity;
8 | import android.app.AlertDialog;
9 | import android.content.ContentValues;
10 | import android.content.DialogInterface;
11 | import android.content.Intent;
12 | import android.content.pm.PackageManager;
13 | import android.content.res.Configuration;
14 | import android.graphics.Color;
15 | import android.net.Uri;
16 | import android.os.Bundle;
17 | import android.os.Environment;
18 | import android.os.Handler;
19 | import android.provider.MediaStore;
20 | import android.provider.Settings;
21 |
22 | import androidx.annotation.Nullable;
23 | import androidx.core.app.ActivityCompat;
24 | import androidx.fragment.app.Fragment;
25 | import androidx.core.content.ContextCompat;
26 | import androidx.core.content.FileProvider;
27 | import androidx.core.os.EnvironmentCompat;
28 | import androidx.appcompat.app.AppCompatActivity;
29 | import androidx.recyclerview.widget.GridLayoutManager;
30 | import androidx.recyclerview.widget.LinearLayoutManager;
31 | import androidx.recyclerview.widget.RecyclerView;
32 | import androidx.recyclerview.widget.SimpleItemAnimator;
33 |
34 | import android.view.KeyEvent;
35 | import android.view.View;
36 | import android.view.Window;
37 | import android.view.WindowManager;
38 | import android.widget.FrameLayout;
39 | import android.widget.TextView;
40 |
41 | import com.donkingliang.imageselector.adapter.FolderAdapter;
42 | import com.donkingliang.imageselector.adapter.ImageAdapter;
43 | import com.donkingliang.imageselector.entry.Folder;
44 | import com.donkingliang.imageselector.entry.Image;
45 | import com.donkingliang.imageselector.entry.RequestConfig;
46 | import com.donkingliang.imageselector.model.ImageModel;
47 | import com.donkingliang.imageselector.utils.DateUtils;
48 | import com.donkingliang.imageselector.utils.ImageSelector;
49 | import com.donkingliang.imageselector.utils.ImageUtil;
50 | import com.donkingliang.imageselector.utils.UriUtils;
51 | import com.donkingliang.imageselector.utils.VersionUtils;
52 |
53 | import java.io.File;
54 | import java.io.IOException;
55 | import java.text.SimpleDateFormat;
56 | import java.util.ArrayList;
57 | import java.util.Date;
58 | import java.util.Locale;
59 |
60 | public class ImageSelectorActivity extends AppCompatActivity {
61 |
62 | private TextView tvTime;
63 | private TextView tvFolderName;
64 | private TextView tvConfirm;
65 | private TextView tvPreview;
66 | private FrameLayout btnConfirm;
67 | private FrameLayout btnPreview;
68 | private RecyclerView rvImage;
69 | private RecyclerView rvFolder;
70 | private View masking;
71 |
72 | private ImageAdapter mAdapter;
73 | private GridLayoutManager mLayoutManager;
74 |
75 | private ArrayList mFolders;
76 | private Folder mFolder;
77 | private boolean applyLoadImage = false;
78 | private boolean applyCamera = false;
79 | private static final int PERMISSION_WRITE_EXTERNAL_REQUEST_CODE = 0x00000011;
80 | private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
81 |
82 | private static final int CAMERA_REQUEST_CODE = 0x00000010;
83 | private Uri mCameraUri;
84 | private String mCameraImagePath;
85 | private long mTakeTime;
86 |
87 | private boolean isOpenFolder;
88 | private boolean isShowTime;
89 | private boolean isInitFolder;
90 | private boolean isSingle;
91 | private boolean canPreview = true;
92 | private int mMaxCount;
93 |
94 | private boolean useCamera = true;
95 | private boolean onlyTakePhoto = false;
96 |
97 | private Handler mHideHandler = new Handler();
98 | private Runnable mHide = new Runnable() {
99 | @Override
100 | public void run() {
101 | hideTime();
102 | }
103 | };
104 |
105 | //用于接收从外面传进来的已选择的图片列表。当用户原来已经有选择过图片,现在重新打开选择器,允许用
106 | // 户把先前选过的图片传进来,并把这些图片默认为选中状态。
107 | private ArrayList mSelectedImages;
108 |
109 | /**
110 | * 启动图片选择器
111 | *
112 | * @param activity
113 | * @param requestCode
114 | * @param config
115 | */
116 | public static void openActivity(Activity activity, int requestCode, RequestConfig config) {
117 | Intent intent = new Intent(activity, ImageSelectorActivity.class);
118 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
119 | activity.startActivityForResult(intent, requestCode);
120 | }
121 |
122 | /**
123 | * 启动图片选择器
124 | *
125 | * @param fragment
126 | * @param requestCode
127 | * @param config
128 | */
129 | public static void openActivity(Fragment fragment, int requestCode, RequestConfig config) {
130 | Intent intent = new Intent(fragment.getActivity(), ImageSelectorActivity.class);
131 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
132 | fragment.startActivityForResult(intent, requestCode);
133 | }
134 |
135 | /**
136 | * 启动图片选择器
137 | *
138 | * @param fragment
139 | * @param requestCode
140 | * @param config
141 | */
142 | public static void openActivity(android.app.Fragment fragment, int requestCode, RequestConfig config) {
143 | Intent intent = new Intent(fragment.getActivity(), ImageSelectorActivity.class);
144 | intent.putExtra(ImageSelector.KEY_CONFIG, config);
145 | fragment.startActivityForResult(intent, requestCode);
146 | }
147 |
148 | @Override
149 | protected void onCreate(@Nullable Bundle savedInstanceState) {
150 | super.onCreate(savedInstanceState);
151 | Intent intent = getIntent();
152 | RequestConfig config = intent.getParcelableExtra(ImageSelector.KEY_CONFIG);
153 | mMaxCount = config.maxSelectCount;
154 | isSingle = config.isSingle;
155 | canPreview = config.canPreview;
156 | useCamera = config.useCamera;
157 | mSelectedImages = config.selected;
158 | onlyTakePhoto = config.onlyTakePhoto;
159 | if (onlyTakePhoto) {
160 | // 仅拍照
161 | checkPermissionAndCamera();
162 | } else {
163 | setContentView(R.layout.activity_image_select);
164 | setStatusBarColor();
165 | initView();
166 | initListener();
167 | initImageList();
168 | checkPermissionAndLoadImages();
169 | hideFolderList();
170 | setSelectImageCount(0);
171 | }
172 | }
173 |
174 | /**
175 | * 修改状态栏颜色
176 | */
177 | private void setStatusBarColor() {
178 | if (VersionUtils.isAndroidL()) {
179 | Window window = getWindow();
180 | window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
181 | window.setStatusBarColor(Color.parseColor("#373c3d"));
182 | }
183 | }
184 |
185 | private void initView() {
186 | rvImage = findViewById(R.id.rv_image);
187 | rvFolder = findViewById(R.id.rv_folder);
188 | tvConfirm = findViewById(R.id.tv_confirm);
189 | tvPreview = findViewById(R.id.tv_preview);
190 | btnConfirm = findViewById(R.id.btn_confirm);
191 | btnPreview = findViewById(R.id.btn_preview);
192 | tvFolderName = findViewById(R.id.tv_folder_name);
193 | tvTime = findViewById(R.id.tv_time);
194 | masking = findViewById(R.id.masking);
195 | }
196 |
197 | private void initListener() {
198 | findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
199 | @Override
200 | public void onClick(View v) {
201 | finish();
202 | }
203 | });
204 |
205 | btnPreview.setOnClickListener(new View.OnClickListener() {
206 | @Override
207 | public void onClick(View v) {
208 | ArrayList images = new ArrayList<>();
209 | images.addAll(mAdapter.getSelectImages());
210 | toPreviewActivity(images, 0);
211 | }
212 | });
213 |
214 | btnConfirm.setOnClickListener(new View.OnClickListener() {
215 | @Override
216 | public void onClick(View v) {
217 | confirm();
218 | }
219 | });
220 |
221 | findViewById(R.id.btn_folder).setOnClickListener(new View.OnClickListener() {
222 | @Override
223 | public void onClick(View v) {
224 | if (isInitFolder) {
225 | if (isOpenFolder) {
226 | closeFolder();
227 | } else {
228 | openFolder();
229 | }
230 | }
231 | }
232 | });
233 |
234 | masking.setOnClickListener(new View.OnClickListener() {
235 | @Override
236 | public void onClick(View v) {
237 | closeFolder();
238 | }
239 | });
240 |
241 | rvImage.addOnScrollListener(new RecyclerView.OnScrollListener() {
242 | @Override
243 | public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
244 | super.onScrollStateChanged(recyclerView, newState);
245 | changeTime();
246 | }
247 |
248 | @Override
249 | public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
250 | super.onScrolled(recyclerView, dx, dy);
251 | changeTime();
252 | }
253 | });
254 | }
255 |
256 | /**
257 | * 初始化图片列表
258 | */
259 | private void initImageList() {
260 | // 判断屏幕方向
261 | Configuration configuration = getResources().getConfiguration();
262 | if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
263 | mLayoutManager = new GridLayoutManager(this, 3);
264 | } else {
265 | mLayoutManager = new GridLayoutManager(this, 5);
266 | }
267 |
268 | rvImage.setLayoutManager(mLayoutManager);
269 | mAdapter = new ImageAdapter(this, mMaxCount, isSingle, canPreview);
270 | rvImage.setAdapter(mAdapter);
271 | ((SimpleItemAnimator) rvImage.getItemAnimator()).setSupportsChangeAnimations(false);
272 | if (mFolders != null && !mFolders.isEmpty()) {
273 | setFolder(mFolders.get(0));
274 | }
275 | mAdapter.setOnImageSelectListener(new ImageAdapter.OnImageSelectListener() {
276 | @Override
277 | public void OnImageSelect(Image image, boolean isSelect, int selectCount) {
278 | setSelectImageCount(selectCount);
279 | }
280 | });
281 | mAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
282 | @Override
283 | public void OnItemClick(Image image, int position) {
284 | toPreviewActivity(mAdapter.getData(), position);
285 | }
286 |
287 | @Override
288 | public void OnCameraClick() {
289 | checkPermissionAndCamera();
290 | }
291 | });
292 | }
293 |
294 | /**
295 | * 初始化图片文件夹列表
296 | */
297 | private void initFolderList() {
298 | if (mFolders != null && !mFolders.isEmpty()) {
299 | isInitFolder = true;
300 | rvFolder.setLayoutManager(new LinearLayoutManager(ImageSelectorActivity.this));
301 | FolderAdapter adapter = new FolderAdapter(ImageSelectorActivity.this, mFolders);
302 | adapter.setOnFolderSelectListener(new FolderAdapter.OnFolderSelectListener() {
303 | @Override
304 | public void OnFolderSelect(Folder folder) {
305 | setFolder(folder);
306 | closeFolder();
307 | }
308 | });
309 | rvFolder.setAdapter(adapter);
310 | }
311 | }
312 |
313 | /**
314 | * 刚开始的时候文件夹列表默认是隐藏的
315 | */
316 | private void hideFolderList() {
317 | rvFolder.post(new Runnable() {
318 | @Override
319 | public void run() {
320 | rvFolder.setTranslationY(rvFolder.getHeight());
321 | rvFolder.setVisibility(View.GONE);
322 | rvFolder.setBackgroundColor(Color.WHITE);
323 | }
324 | });
325 | }
326 |
327 | /**
328 | * 设置选中的文件夹,同时刷新图片列表
329 | *
330 | * @param folder
331 | */
332 | private void setFolder(Folder folder) {
333 | if (folder != null && mAdapter != null && !folder.equals(mFolder)) {
334 | mFolder = folder;
335 | tvFolderName.setText(folder.getName());
336 | rvImage.scrollToPosition(0);
337 | mAdapter.refresh(folder.getImages(), folder.isUseCamera());
338 | }
339 | }
340 |
341 | private void setSelectImageCount(int count) {
342 | if (count == 0) {
343 | btnConfirm.setEnabled(false);
344 | btnPreview.setEnabled(false);
345 | tvConfirm.setText(R.string.selector_send);
346 | tvPreview.setText(R.string.selector_preview);
347 | } else {
348 | btnConfirm.setEnabled(true);
349 | btnPreview.setEnabled(true);
350 | tvPreview.setText(getString(R.string.selector_preview) + "(" + count + ")");
351 | if (isSingle) {
352 | tvConfirm.setText(R.string.selector_send);
353 | } else if (mMaxCount > 0) {
354 | tvConfirm.setText(getString(R.string.selector_send) + "(" + count + "/" + mMaxCount + ")");
355 | } else {
356 | tvConfirm.setText(getString(R.string.selector_send) + "(" + count + ")");
357 | }
358 | }
359 | }
360 |
361 | /**
362 | * 弹出文件夹列表
363 | */
364 | private void openFolder() {
365 | if (!isOpenFolder) {
366 | masking.setVisibility(View.VISIBLE);
367 | ObjectAnimator animator = ObjectAnimator.ofFloat(rvFolder, "translationY",
368 | rvFolder.getHeight(), 0).setDuration(300);
369 | animator.addListener(new AnimatorListenerAdapter() {
370 | @Override
371 | public void onAnimationStart(Animator animation) {
372 | super.onAnimationStart(animation);
373 | rvFolder.setVisibility(View.VISIBLE);
374 | }
375 | });
376 | animator.start();
377 | isOpenFolder = true;
378 | }
379 | }
380 |
381 | /**
382 | * 收起文件夹列表
383 | */
384 | private void closeFolder() {
385 | if (isOpenFolder) {
386 | masking.setVisibility(View.GONE);
387 | ObjectAnimator animator = ObjectAnimator.ofFloat(rvFolder, "translationY",
388 | 0, rvFolder.getHeight()).setDuration(300);
389 | animator.addListener(new AnimatorListenerAdapter() {
390 | @Override
391 | public void onAnimationEnd(Animator animation) {
392 | super.onAnimationEnd(animation);
393 | rvFolder.setVisibility(View.GONE);
394 | }
395 | });
396 | animator.start();
397 | isOpenFolder = false;
398 | }
399 | }
400 |
401 | /**
402 | * 隐藏时间条
403 | */
404 | private void hideTime() {
405 | if (isShowTime) {
406 | ObjectAnimator.ofFloat(tvTime, "alpha", 1, 0).setDuration(300).start();
407 | isShowTime = false;
408 | }
409 | }
410 |
411 | /**
412 | * 显示时间条
413 | */
414 | private void showTime() {
415 | if (!isShowTime) {
416 | ObjectAnimator.ofFloat(tvTime, "alpha", 0, 1).setDuration(300).start();
417 | isShowTime = true;
418 | }
419 | }
420 |
421 | /**
422 | * 改变时间条显示的时间(显示图片列表中的第一个可见图片的时间)
423 | */
424 | private void changeTime() {
425 | int firstVisibleItem = getFirstVisibleItem();
426 | Image image = mAdapter.getFirstVisibleImage(firstVisibleItem);
427 | if (image != null) {
428 | String time = DateUtils.getImageTime(this, image.getTime());
429 | tvTime.setText(time);
430 | showTime();
431 | mHideHandler.removeCallbacks(mHide);
432 | mHideHandler.postDelayed(mHide, 1500);
433 | }
434 | }
435 |
436 | private int getFirstVisibleItem() {
437 | return mLayoutManager.findFirstVisibleItemPosition();
438 | }
439 |
440 | private void confirm() {
441 | if (mAdapter == null) {
442 | return;
443 | }
444 | //因为图片的实体类是Image,而我们返回的是String数组,所以要进行转换。
445 | ArrayList selectImages = mAdapter.getSelectImages();
446 | ArrayList images = new ArrayList<>();
447 | for (Image image : selectImages) {
448 | images.add(image.getPath());
449 | }
450 | saveImageAndFinish(images, false);
451 | }
452 |
453 | private void saveImageAndFinish(final ArrayList images, final boolean isCameraImage) {
454 |
455 | //点击确定,把选中的图片通过Intent传给上一个Activity。
456 | setResult(images, isCameraImage);
457 | finish();
458 | }
459 |
460 | private void setResult(ArrayList images, boolean isCameraImage) {
461 | Intent intent = new Intent();
462 | intent.putStringArrayListExtra(ImageSelector.SELECT_RESULT, images);
463 | intent.putExtra(ImageSelector.IS_CAMERA_IMAGE, isCameraImage);
464 | setResult(RESULT_OK, intent);
465 | }
466 |
467 | private void toPreviewActivity(ArrayList images, int position) {
468 | if (images != null && !images.isEmpty()) {
469 | PreviewActivity.openActivity(this, images,
470 | mAdapter.getSelectImages(), isSingle, mMaxCount, position);
471 | }
472 | }
473 |
474 | @Override
475 | protected void onStart() {
476 | super.onStart();
477 | if (applyLoadImage) {
478 | applyLoadImage = false;
479 | checkPermissionAndLoadImages();
480 | }
481 | if (applyCamera) {
482 | applyCamera = false;
483 | checkPermissionAndCamera();
484 | }
485 | }
486 |
487 | /**
488 | * 处理图片预览页返回的结果
489 | *
490 | * @param requestCode
491 | * @param resultCode
492 | * @param data
493 | */
494 | @Override
495 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
496 | super.onActivityResult(requestCode, resultCode, data);
497 | if (requestCode == ImageSelector.RESULT_CODE) {
498 | if (data != null && data.getBooleanExtra(ImageSelector.IS_CONFIRM, false)) {
499 | //如果用户在预览页点击了确定,就直接把用户选中的图片返回给用户。
500 | confirm();
501 | } else {
502 | //否则,就刷新当前页面。
503 | mAdapter.notifyDataSetChanged();
504 | setSelectImageCount(mAdapter.getSelectImages().size());
505 | }
506 | } else if (requestCode == CAMERA_REQUEST_CODE) {
507 | if (resultCode == RESULT_OK) {
508 | ArrayList images = new ArrayList<>();
509 | Uri savePictureUri = null;
510 | if (VersionUtils.isAndroidQ()) {
511 | savePictureUri = mCameraUri;
512 | images.add(UriUtils.getPathForUri(this, mCameraUri));
513 | } else {
514 | savePictureUri = Uri.fromFile(new File(mCameraImagePath));
515 | images.add(mCameraImagePath);
516 | }
517 | ImageUtil.savePicture(this,savePictureUri,mTakeTime);
518 | saveImageAndFinish(images, true);
519 | } else {
520 | if (onlyTakePhoto) {
521 | finish();
522 | }
523 | }
524 | }
525 | }
526 |
527 | /**
528 | * 横竖屏切换处理
529 | *
530 | * @param newConfig
531 | */
532 | @Override
533 | public void onConfigurationChanged(Configuration newConfig) {
534 | super.onConfigurationChanged(newConfig);
535 | if (mLayoutManager != null && mAdapter != null) {
536 | //切换为竖屏
537 | if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
538 | mLayoutManager.setSpanCount(3);
539 | }
540 | //切换为横屏
541 | else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
542 | mLayoutManager.setSpanCount(5);
543 | }
544 | mAdapter.notifyDataSetChanged();
545 | }
546 | }
547 |
548 | /**
549 | * 检查权限并加载SD卡里的图片。
550 | */
551 | private void checkPermissionAndLoadImages() {
552 | if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
553 | // Toast.makeText(this, "没有图片", Toast.LENGTH_LONG).show();
554 | return;
555 | }
556 | int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
557 | Manifest.permission.WRITE_EXTERNAL_STORAGE);
558 | if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
559 | //有权限,加载图片。
560 | loadImageForSDCard();
561 | } else {
562 | //没有权限,申请权限。
563 | ActivityCompat.requestPermissions(ImageSelectorActivity.this,
564 | new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
565 | }
566 | }
567 |
568 | /**
569 | * 检查权限并拍照。
570 | */
571 | private void checkPermissionAndCamera() {
572 | int hasCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
573 | int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
574 | Manifest.permission.WRITE_EXTERNAL_STORAGE);
575 | if (hasCameraPermission == PackageManager.PERMISSION_GRANTED
576 | && hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
577 | //有调起相机拍照。
578 | openCamera();
579 | } else {
580 | //没有权限,申请权限。
581 | ActivityCompat.requestPermissions(ImageSelectorActivity.this,
582 | new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA_REQUEST_CODE);
583 | }
584 | }
585 |
586 | /**
587 | * 处理权限申请的回调。
588 | *
589 | * @param requestCode
590 | * @param permissions
591 | * @param grantResults
592 | */
593 | @Override
594 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
595 | if (requestCode == PERMISSION_WRITE_EXTERNAL_REQUEST_CODE) {
596 | if (grantResults.length > 0
597 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
598 | //允许权限,加载图片。
599 | loadImageForSDCard();
600 | } else {
601 | //拒绝权限,弹出提示框。
602 | showExceptionDialog(true);
603 | }
604 | } else if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
605 | if (grantResults.length > 1
606 | && grantResults[0] == PackageManager.PERMISSION_GRANTED
607 | && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
608 | //允许权限,有调起相机拍照。
609 | openCamera();
610 | } else {
611 | //拒绝权限,弹出提示框。
612 | showExceptionDialog(false);
613 | }
614 | }
615 | }
616 |
617 | /**
618 | * 发生没有权限等异常时,显示一个提示dialog.
619 | */
620 | private void showExceptionDialog(final boolean applyLoad) {
621 | new AlertDialog.Builder(this)
622 | .setCancelable(false)
623 | .setTitle(R.string.selector_hint)
624 | .setMessage(R.string.selector_permissions_hint)
625 | .setNegativeButton(R.string.selector_cancel, new DialogInterface.OnClickListener() {
626 | @Override
627 | public void onClick(DialogInterface dialog, int which) {
628 | dialog.cancel();
629 | finish();
630 | }
631 | }).setPositiveButton(R.string.selector_confirm, new DialogInterface.OnClickListener() {
632 | @Override
633 | public void onClick(DialogInterface dialog, int which) {
634 | dialog.cancel();
635 | startAppSettings();
636 | if (applyLoad) {
637 | applyLoadImage = true;
638 | } else {
639 | applyCamera = true;
640 | }
641 | }
642 | }).show();
643 | }
644 |
645 | /**
646 | * 从SDCard加载图片。
647 | */
648 | private void loadImageForSDCard() {
649 | ImageModel.loadImageForSDCard(this, new ImageModel.DataCallback() {
650 | @Override
651 | public void onSuccess(ArrayList folders) {
652 | mFolders = folders;
653 | runOnUiThread(new Runnable() {
654 | @Override
655 | public void run() {
656 | if (mFolders != null && !mFolders.isEmpty()) {
657 | initFolderList();
658 | mFolders.get(0).setUseCamera(useCamera);
659 | setFolder(mFolders.get(0));
660 | if (mSelectedImages != null && mAdapter != null) {
661 | mAdapter.setSelectedImages(mSelectedImages);
662 | mSelectedImages = null;
663 | setSelectImageCount(mAdapter.getSelectImages().size());
664 | }
665 | }
666 | }
667 | });
668 | }
669 | });
670 | }
671 |
672 | /**
673 | * 调起相机拍照
674 | */
675 | private void openCamera() {
676 | Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
677 | if (captureIntent.resolveActivity(getPackageManager()) != null) {
678 | File photoFile = null;
679 | Uri photoUri = null;
680 |
681 | if (VersionUtils.isAndroidQ()) {
682 | photoUri = createImagePathUri();
683 | } else {
684 | try {
685 | photoFile = createImageFile();
686 | } catch (IOException e) {
687 | e.printStackTrace();
688 | }
689 |
690 | if (photoFile != null) {
691 | mCameraImagePath = photoFile.getAbsolutePath();
692 | if (VersionUtils.isAndroidN()) {
693 | //通过FileProvider创建一个content类型的Uri
694 | photoUri = FileProvider.getUriForFile(this, getPackageName() + ".imageSelectorProvider", photoFile);
695 | } else {
696 | photoUri = Uri.fromFile(photoFile);
697 | }
698 | }
699 | }
700 |
701 | mCameraUri = photoUri;
702 | if (photoUri != null) {
703 | captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
704 | captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
705 | startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
706 | mTakeTime = System.currentTimeMillis();
707 | }
708 | }
709 | }
710 |
711 | /**
712 | * 创建一条图片地址uri,用于保存拍照后的照片
713 | *
714 | * @return 图片的uri
715 | */
716 | public Uri createImagePathUri() {
717 | String status = Environment.getExternalStorageState();
718 | SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
719 | long time = System.currentTimeMillis();
720 | String imageName = timeFormatter.format(new Date(time));
721 | // ContentValues是我们希望这条记录被创建时包含的数据信息
722 | ContentValues values = new ContentValues(2);
723 | values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
724 | values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
725 | // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
726 | if (status.equals(Environment.MEDIA_MOUNTED)) {
727 | return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
728 | } else {
729 | return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
730 | }
731 | }
732 |
733 | private File createImageFile() throws IOException {
734 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
735 | String imageFileName = String.format("JPEG_%s.jpg", timeStamp);
736 | File storageDir = Environment.getExternalStoragePublicDirectory(
737 | Environment.DIRECTORY_PICTURES);
738 | if (!storageDir.exists()) {
739 | storageDir.mkdir();
740 | }
741 | File tempFile = new File(storageDir, imageFileName);
742 | if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
743 | return null;
744 | }
745 | return tempFile;
746 | }
747 |
748 | /**
749 | * 启动应用的设置
750 | */
751 | private void startAppSettings() {
752 | Intent intent = new Intent(
753 | Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
754 | intent.setData(Uri.parse("package:" + getPackageName()));
755 | startActivity(intent);
756 | }
757 |
758 | @Override
759 | public boolean onKeyDown(int keyCode, KeyEvent event) {
760 | if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && isOpenFolder) {
761 | closeFolder();
762 | return true;
763 | }
764 | return super.onKeyDown(keyCode, event);
765 | }
766 | }
767 |
--------------------------------------------------------------------------------