前言:这次带来的是使用RxPermissions+知乎图片选择器Matisse+图片压缩工具Luban实现图片选择的功能。
1 | implementation 'com.zhihu.android:matisse:0.5.1' |
1.首先在RxPermissions申请完权限后开启知乎图片选择器(注意:使用知乎开源框架Matisse需注意的地方)
1 | RxPermissions rxPermissions=new RxPermissions(this); |
2.在onActivityResult方法中用Luban进行图片压缩处理
1 |
|
这里需要我使用了一个工具类将Uri转为File1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46public class FileUtil {
public static File getFileByUri(Uri uri, Context context) {
String path = null;
if ("file".equals(uri.getScheme())) {
path = uri.getEncodedPath();
if (path != null) {
path = Uri.decode(path);
ContentResolver cr = context.getContentResolver();
StringBuffer buff = new StringBuffer();
buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null);
int index = 0;
int dataIdx = 0;
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
index = cur.getInt(index);
dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cur.getString(dataIdx);
}
cur.close();
if (index == 0) {
} else {
Uri u = Uri.parse("content://media/external/images/media/" + index);
System.out.println("temp uri is :" + u);
}
}
if (path != null) {
return new File(path);
}
} else if ("content".equals(uri.getScheme())) {
// 4.2.2以后
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
path = cursor.getString(columnIndex);
}
cursor.close();
return new File(path);
} else {
//Log.i(TAG, "Uri Scheme:" + uri.getScheme());
}
return null;
}
}