手机拍照与相册获取,很多人都不陌生,但是偏偏这个最常见的功能却让我好一个整理
手机拍照
手机拍照最常用的就是这个方法
protected void getImageFromCamera() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
}
else {
Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
}
}
获取的数据的数据在
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_IMAGE) {
Uri uri = data.getData();
} else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA ) {
Uri uri = data.getData();
} }
在这个过程过程中可能会遇到 拍照获得的uri为null ,这个不是本文的重点,解决方法参见
http://blog.csdn.net/beyond0525/article/details/8939984
相册获取
这个功能的方法为
protected void getImageFromAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//相片类型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
其实很简单 但是如果你的手机是Android4.4及以上手机 就会发现获取不到图片真实的路径.这是因为Android4.4的图片路径获取,如果回来的Uri的格式有两种:
1.content://com.android.providers.media.documents/document/image:3951
2.content://media/external/images/media/3951
解决方法如下:
/**
*
* android 4.4以后获取图片
* @param uri
* @param activity
* @return
*/
public static String uri2filePath(Uri uri, Activity activity) {
String path = "";
if (DocumentsContract.isDocumentUri(activity, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = activity.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
path = cursor.getString(columnIndex);
}
cursor.close();
} else {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.getContentResolver().query(uri,
projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
}
return path;
}
如果你无法判断手机的版本 可以做以下判断
Uri uri = data.getData();
if(uri != null){
if (android.os.Build.VERSION.SDK_INT>18) {
String realPath = uri2filePath(uri,CourseAddQuestionActivity.this);
setImageView(realPath);
}else {
//Android4.4以前获取方法
String realPath = getRealPathFromURI(uri);
T.showShort(mContext, "获取图片成功,path="+realPath);
setImageView(realPath);
}
}else{
Log.e(TAG, "从相册获取图片失败");
}