I'm writing a simple image viewer for Android. My app have the "Open file from Gallery" button. So, when I've choosed the image from Gallery, it must return the path to file into my app, but it return a strange Uri, which looks like content://media/storage/2ch/30128
.
How I can get an absolute file path from this Uri?
Here's some code for launching Gallery:
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Выберите файл"), PICTURE_REQUEST_CODE);
P.S. Excuse for my English
Use this code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
}
You can also get image using URI :
try this
try {
Uri selectedImage = selectedImageUri;
//getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
rptImage.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
OR simply this :
Try with:
ImageView.setImageUri(Uri.fromFile(new File("/sdcard/cats.jpg")));
Or with:
ImageView.setImageUri(Uri.parse(new File("/sdcard/cats.jpg").toString()));
try below code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_FILE && resultCode == Activity.RESULT_OK) {
Uri mImageCaptureUri = data.getData();
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
}
}
}
here variable path will return path to your selected image.