Android获取手机或者内存卡里面的图片有两种方式
1.这是通过一种action
Intent intent=new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, MAIN_PIC);
2.这是通过另一个中action
Intent intent=new Intent();
intent.setAction(Intent.ACTION_PICK);
//EXTERNAL_CONTENT_URI 是外部的存储uri
// INTERNAL_CONTENT_URI是内部的存储uri
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, MAIN_PIC);
然后在onActivityResult里面进行操作
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
imageview.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* 将Bitmap设定到ImageView */
String[] proj = {MediaStore.Images.Media.DATA};
//好像是android多媒体数据库的封装接口,具体的看Android文档
Cursor cursor = managedQuery(uri, proj, null, null, null);
//按我个人理解 这个是获得用户选择的图片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
//最后根据索引值获取图片路径
String path = cursor.getString(column_index);
Toast.makeText(this, path, 1).show();
}
得到uri之后,一般需要查询,然后得到结果集,里面就是图片的路径。
case REQ_CODE_PICTURE:
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null,
null, null);
cursor.moveToFirst();
try {
srcpath = cursor.getString(1);
Log.i("OnActivtyResult",
"File path :[" + cursor.getColumnCount() + srcpath
+ "]");
//MediaStore.Images.Media.DATA
InputStream is = new FileInputStream(cursor.getString(1));
Bitmap bmp = ImageLoader.createBitmap(is, 1);
ivIcon.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
protected String getAbsoluteImagePath(Uri uri) {
// can post image
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
// 如果游标为空说明获取的已经是绝对路径了
return uri.getPath();
}
}