寫項目的時候一般都會用到頭像選擇功能,現在整理一下.
需求: 頭像選擇需要有兩個選項:
- 從手機拍照獲取;
- 從相冊中獲取。
效果如下:
這里寫圖片描述
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及以上和以下會有不同,要分開處理。