在 最新开源作品 大开Note
地址:https://github.com/mhgd3250905/DaKaiNote
中有需要点击进入相册 然后对图片进行选择 然后显示在布局中 ,代码如下:
// 激活系统图库,选择一张图片
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
在Activity中获取返回值
if (resultCode == RESULT_OK){
switch (requestCode){
case PHOTO_REQUEST_GALLERY:
if (data!=null){
fl_note_iamge.setVisibility(View.VISIBLE);
//设置图片存在
isImageExist = true;
Uri uriImageFromGallery = data.getData();
LogUtils.Log(CameraImageUtils.getAbsoluteImagePath(ArcNewNoteActivity.this,
uriImageFromGallery));
ImageCache imageCacheGallery = new ImageCache();
imageCacheGallery.setNoteKey(noteKey);
imageCacheGallery.setImagePath(CameraImageUtils.getAbsoluteImagePath(ArcNewNoteActivity.this,
uriImageFromGallery));
imageCacheGallery.save();
//获取当前fragment
mImageNewNoteFragment.insertImage(noteKey);
}
break;
}
}
这里通过一个方法 来通过图片Uri来获取图片的绝对路径
这个方法如下:
/**
* 通过uri获取文件的绝对路径
*
* @param uri
* @return
*/
private String getAbsoluteImagePath(Uri uri) {
String imagePath = "";
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = MainActivity.this.managedQuery(uri, proj, // Which
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);
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
imagePath = cursor.getString(column_index);
}
}
return imagePath;
}