1、将 Uri 转化为 path

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String uriToPath(Uri uri,Activity context) {
// 新建一个字符串数组用于存储图片地址数据。
String[] proj = { MediaStore.Images.Media.DATA };
// android系统提供的接口,用于根据uri获取数据
// Cursor cursor = context.managedQuery(uri, proj, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
// 获得用户选择图片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// 将游标移至开头 ,防止引起队列越界
cursor.moveToFirst();
// 根据索引值获取图片路径
String path = cursor.getString(column_index);
return path;
}

2、根据Uri生成Bitmap

1
2
3
4
5
6
7
8
9
10
11
12
public Bitmap getBitmap(Uri uri,Activity context) {
Bitmap bm = null;
// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
ContentResolver resolver = context.getContentResolver();
try {
//根据图片的URi生成bitmap
bm = MediaStore.Images.Media.getBitmap(resolver, uri);
} catch (IOException e) {
Log.e("getImg", e.toString());
}
return bm;
}

3、将彩色图片转化为黑白色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public Bitmap convertToBlackWhite(Bitmap bmp) {
int width = bmp.getWidth(); // 获取位图的宽
int height = bmp.getHeight(); // 获取位图的高
int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

bmp.getPixels(pixels, 0, width, 0, 0, width, height);
int alpha = 0xFF << 24;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = pixels[width * i + j];

//分离三原色
int red = ((grey & 0x00FF0000) >> 16);
int green = ((grey & 0x0000FF00) >> 8);
int blue = (grey & 0x000000FF);

//转化成灰度像素
grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
grey = alpha | (grey << 16) | (grey << 8) | grey;
pixels[width * i + j] = grey;
}
}
//新建图片
Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
//设置图片数据
newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

Bitmap bitmap = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);
return bitmap;
}