头像设置主要有两种方式,从相册中选择照片,或直接拍照。选好照片后,都需要对照片进行裁剪,并且保存和显示。
1. 变量
private static final int ALBUM_RET_CODE = 1;
private static final int CAMERA_RET_CODE = 2;
private static final int FINISH_RET_CODE = 3;
private static final String PHOTO_NAME = "talking_photo.jpg";
2. 打开相册和拍照
/**打开相册*/
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
//返回时将结果也返回
startActivityForResult(intent,ALBUM_RET_CODE);
/**拍照*/
// 判断存储卡是否可以用,可用进行存储
if (!hasSdCard()) {
Toast.makeText(mContext,R.string.toast_sdcard_invalid,Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(),PHOTO_NAME)));
//返回时将结果也返回
startActivityForResult(intent,CAMERA_RET_CODE);
public static boolean hasSdCard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
这两个操作需要在AndroidManifest.xml文件中添加SDK卡的读写权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
3. 将相册或拍照选中的照片进行裁剪
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
// 从相册获取
case ALBUM_RET_CODE:
startPhotoZoom(data.getData());
break;
// 相机拍照
case CAMERA_RET_CODE:
File temp = new File(Environment.getExternalStorageDirectory()+ "/" + PHOTO_NAME);
startPhotoZoom(Uri.fromFile(temp));
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**裁剪照片*/
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 下面这个crop=true是设置在开启的Intent中设置显示的view可裁剪
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, FINISH_RET_CODE);
}
4. 将裁剪得到的图片进行保存或显示
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
//...
// 取得裁剪后的图片
case FINISH_RET_CODE:
/**
* 非空判断一定要验证
*如果不验证的话,在剪裁之后如果发现不满意,丢弃当前照片时,会报NullException
*/
if (data != null) {
setPicToView(data);
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
Drawable drawable = new BitmapDrawable(photo);
mPhotoImage.setImageDrawable(drawable);
}
}
这部分代码比较简单,不过还算比较常用,所以特地写出来。