很多项目中都会使用到选择图片、对图片进行剪切的功能。SDK为我们提供了一整套的处理接口,可以不用再自己写这些繁琐的代码了。
```
//打开相册
private voidopeanPhotoalbum() {
Intentintent1=newIntent(Intent.ACTION_PICK, null);
intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent1,1);
}
//打开相机
private voidopeanCamera() {
Intentintent2=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(newFile(Environment.getExternalStorageDirectory(),
"head.jpg")));
startActivityForResult(intent2,2);//采用ForResult打开
}
//在返回接口中处理
protected voidonActivityResult(intrequestCode, intresultCode,Intent data) {
switch(requestCode) {
case1:
if(resultCode ==RESULT_OK) {
cropPhoto(data.getData());//裁剪图片
}
break;
case2:
if(resultCode ==RESULT_OK) {
Filetemp=newFile(Environment.getExternalStorageDirectory()
+"/head.jpg");
cropPhoto(Uri.fromFile(temp));
}//裁剪图片
break;
case3:
if(data !=null) {
Bundleextras= data.getExtras();
head=extras.getParcelable("data");
if(head!=null) {
/**
* 上传服务器代码
*/
HeadImageViewUtils.setPicToView(head,path);
sendImage(head,actionUrl);
head= HeadImageViewUtils.compressImage(head,100);
mCircleImageView.setImageBitmap(head);
}else{
//mRequest.personalDataRequests(uid, this);
}
}
break;
}
}
/**
* 调用系统的裁剪
*
*@paramuri
*/
public voidcropPhoto(Uri uri) {
Intentintent=newIntent("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",150);
intent.putExtra("outputY",150);
intent.putExtra("return-data", true);
startActivityForResult(intent,3);
}
startActivityForResult(intent2,2);//采用ForResult打开
}
```