//请求识别码
private static final int CODE_GALLERY_REQUEST = 0xa0;
private static final int CODE_RESULT_REQUEST = 0xa2;
// 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
private static int output_X = 480;
private static int output_Y = 480;
// 从相册选取图片作为头像
private void choseAvatarFromGallery() {
Intent intent = new Intent();
// 设置文件的类型
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, CODE_GALLERY_REQUEST);
}
/*
* 裁剪选择的图片
*/
public void cropRawPhoto(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX , aspectY :宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX , outputY : 裁剪图片宽高
intent.putExtra("outputX", output_X);
intent.putExtra("outputY", output_Y);
intent.putExtra("return-data", true);
startActivityForResult(intent, CODE_RESULT_REQUEST);
}
/**
* 提取保存裁剪之后的图片数据,并设置头像部分的View
*/
private void setImageToHeadView(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
revise_avatar.setImageBitmap(photo);
}
}
//返回结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 用户没有进行有效的设置操作,返回
if (resultCode == RESULT_CANCELED) {
ToastUtils.showToast(Revise_personaldata.this, "取消", Toast.LENGTH_LONG);
}
switch (requestCode){
case CODE_GALLERY_REQUEST:
cropRawPhoto(data.getData());
break;
case CODE_RESULT_REQUEST:
setImageToHeadView(data);
break;
}
}