写项目的时候一般都会用到头像选择功能,现在整理一下.
需求: 头像选择需要有两个选项:
- 从手机拍照获取;
- 从相册中获取。
效果如下:
这里写图片描述Demo地址:https://github.com/KeithLanding/ImagePicker
关键代码:
一. 调起相册
public void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
//判断系统中是否有处理该Intent的Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_GET);
} else {
showToast("未找到图片查看器");
}
}
二. 调起相机
private void dispatchTakePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断系统中是否有处理该Intent的Activity
if (intent.resolveActivity(getPackageManager()) != null) {
// 创建文件来保存拍的照片
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// 异常处理
}
if (photoFile != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
} else {
showToast("无法启动相机");
}
}
/**
* 创建新文件
*
* @return
* @throws IOException
*/
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* 文件名 */
".jpg", /* 后缀 */
storageDir /* 路径 */
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
三. 处理返回结果
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 回调成功
if (resultCode == RESULT_OK) {
String filePath = null;
//判断是哪一个的回调
if (requestCode == REQUEST_IMAGE_GET) {
//返回的是content://的样式
filePath = getFilePathFromContentUri(data.getData(), this);
} else if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (mCurrentPhotoPath != null) {
filePath = mCurrentPhotoPath;
}
}
if (!TextUtils.isEmpty(filePath)) {
// 自定义大小,防止OOM
Bitmap bitmap = getSmallBitmap(filePath, 200, 200);
mAvatar.setImageBitmap(bitmap);
}
}
}
/**
* @param uri content:// 样式
* @param context
* @return real file path
*/
public static String getFilePathFromContentUri(Uri uri, Context context) {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor == null) return null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
/**
* 获取小图片,防止OOM
*
* @param filePath
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeFile(filePath, options);
} catch (Exception e) {
e.printStackTrace();
}
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
/**
* 计算图片缩放比例
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
注意事项:
- 读写权限要加上:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 调起相册时,Intent用的Action是Intent.ACTION_PICK,而不是 ACTION_GET_CONTENT,使用后者返回uri在android 4.4及以上和以下会有不同,要分开处理。
网友评论
还有,有的手机拍照后并没有保存到相册中,导致得到的图片只是个缩略图。
2. 如果调用手机拍照,我已经调用了createImageFile()创建了新的文件,拍完照将自动保存在该文件路径。