前言
Android应用中经常会遇到上传相册图片的需求,这里记录一下如何进行相册图片的选取和裁剪。
相册选取图片
1. 激活相册或是文件管理器,来获取相片,代码如下:
1
2
3
4
5
6
|
private static final int TAKE_PICTURE_FROM_ALBUM = 1 ;
private void takePictureFromAlbum() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType( "image/*" );
startActivityForResult(intent, TAKE_PICTURE_FROM_ALBUM);
}
|
2. 通过startAcitivityForResult()方法,我们可以在onAcitivityResult()中来获取图片的URI,然后将图片的URI传递给图片裁剪函数,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case TAKE_PICTURE_FROM_ALBUM:
if (data != null ) {
cropPictureFromAlbum(data.getData());
}
break ;
case PICTURE_CROP_CODE:
if (data != null ) {
// 这是裁剪后图片的bitmap
Bitmap bitmap = data.getParcelableExtra( "data" );
}
break ;
default :
break ;
}
}
}
private static final int TAKE_PICTURE_FROM_ALBUM = 1 ;
private void takePictureFromAlbum() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType( "image/*" );
startActivityForResult(intent, TAKE_PICTURE_FROM_ALBUM);
}
private static final int PICTURE_CROP_CODE = 2 ;
private void cropPictureFromAlbum(Uri pictureUri) {
Intent intent = new Intent( "com.android.camera.action.CROP" );
intent.setDataAndType(pictureUri, "image/*" );
intent.putExtra( "crop" , "true" );
// 裁剪框比例
intent.putExtra( "aspectX" , 1 );
intent.putExtra( "aspectY" , 2 );
// 裁剪后输入图片的尺寸大小
intent.putExtra( "outputX" , 300 );
intent.putExtra( "outputY" , 300 );
// 取消人脸识别
intent.putExtra( "noFaceDetection" , true );
intent.putExtra( "return-data" , true );
startActivityForResult(intent, PICTURE_CROP_CODE);
}
|
3. 在onActivityResult里,通过data.getParcelableExtra("data")可以获取图片裁剪之后的bitmap,之后就可以将bitmap赋值给图片控件了。