Android打開系統(tǒng)拍照&相冊(cè)獲取頭像
現(xiàn)在許多應(yīng)用都有上傳頭像的功能涛菠,再次奉上代開系統(tǒng)相冊(cè)或打開系統(tǒng)相機(jī)拍照的實(shí)現(xiàn),有的同學(xué)在測(cè)試小米手機(jī)上打開選擇相冊(cè)有奔潰,此代碼已完美解決此問題...
樓主,做的頭像需要經(jīng)過裁剪之后和圓形處理...
1.設(shè)置點(diǎn)擊打開相機(jī)&打開系統(tǒng)圖庫
@Override
public void onClick(View v) {
// 打開系統(tǒng)拍照程
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA);
}
@Override
public void onClick(View v) {
// 打開系統(tǒng)圖庫選擇圖片
Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, PICTURE);
}
2.重寫帶結(jié)果啟動(dòng)的回調(diào)onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA && resultCode == RESULT_OK && data != null) {
// 拍照
Bundle bundle = data.getExtras();
// 獲取相機(jī)返回的數(shù)據(jù),并轉(zhuǎn)換為圖片格式
Bitmap bitmap = (Bitmap) bundle.get("data");
// bitmap圓形裁剪
// bitmap = BitmapUtils.zoom(bitmap, DensityUtil.dp2px(this, 62), DensityUtil.dp2px(this, 62));
bitmap = BitmapUtils.zoom(bitmap, DensityUtil.dp2px(this, 20), DensityUtil.dp2px(this, 20));
Bitmap circleBitmap = BitmapUtils.circleBitmap(bitmap);
//TODO 將圖片上傳到服務(wù)器
// ivIcon.setImageBitmap(circleBitmap);
uploadHeadpic(bitmap);
// 將圖片保存在本地
try {
saveImage(circleBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else if (requestCode == PICTURE && resultCode == RESULT_OK && data != null) {
//圖庫
String pathResult = null; // 獲取圖片路徑的方法調(diào)用
try {
Uri uri = data.getData();
pathResult = getPath(uri);
Log.e("TAG", "圖片路徑===" + pathResult);
} catch (Exception e) {
e.printStackTrace();
}
//這里返回的uri情況就有點(diǎn)多了
//**:在4.4.2之前返回的uri是:content://media/external/images/media/3951或者file://....在4.4.2返回的是content://com.android.providers.media.documents/document/image:3951或者
//總結(jié):uri的組成告抄,eg:content://com.example.project:200/folder/subfolder/etc
//content:--->"scheme"
//com.example.project:200-->"host":"port"--->"authority"[主機(jī)地址+端口(省略) =authority]
//folder/subfolder/etc-->"path" 路徑部分
//android各個(gè)不同的系統(tǒng)版本,對(duì)于獲取外部存儲(chǔ)上的資源,返回的Uri對(duì)象都可能各不一樣,所以要保證無論是哪個(gè)系統(tǒng)版本都能正確獲取到圖片資源的話
//就需要針對(duì)各種情況進(jìn)行一個(gè)處理了
Bitmap decodeFile = BitmapFactory.decodeFile(pathResult);
Bitmap zoomBitmap = BitmapUtils.zoom(decodeFile, DensityUtil.dp2px(this, 20), DensityUtil.dp2px(this, 20));
// bitmap圓形裁剪p
Bitmap circleImage = BitmapUtils.circleBitmap(zoomBitmap);
// 真實(shí)項(xiàng)目當(dāng)中嵌牺,是需要上傳到服務(wù)器的..這步我們就不做了打洼。
uploadHeadpic(zoomBitmap);
try {
// 保存圖片到本地
saveImage(circleImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
3.獲取圖片路徑
// 根據(jù)系統(tǒng)相冊(cè)選擇的文件獲取路徑
@SuppressLint("NewApi")
private String getPath(Uri uri) {
// int sdkVersion = Build.VERSION.SDK_INT;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// 高于4.4.2的版本
// if (sdkVersion >= 19) {
if (isKitKat && DocumentsContract.isDocumentUri(mContext, uri)) {
Log.e("TAG", "uri auth: " + uri.getAuthority());
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(this, contentUri, null, null);
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(this, contentUri, selection, selectionArgs);
} else if (isMedia(uri)) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = this.managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
return actualimagecursor.getString(actual_image_column_index);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(this, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) { // File
return uri.getPath();
}
return null;
}
private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isMedia(Uri uri) {
return "media".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
以上就是比較完整的代碼了...
Thanks all.
本文首發(fā)于我的微信公眾號(hào),更多干貨文章逆粹,請(qǐng)掃描二維碼訂閱哦:
您可以掃描上面的二維碼募疮,來關(guān)注我的微信公眾號(hào),來學(xué)習(xí)更多的干貨文章枯饿!
另外酝锅,我還建了一個(gè)免費(fèi)的知識(shí)星球,感興趣的微信掃碼即可加入奢方!