I am trying to get the path of Gallery Image. I am getting the path of the image which is stored in internal storage but not of the external storage. I have also enabled the
I want to get the selected image path which I have choose from gallery
The problem is that change Android.Net.Uri
to path
, here is an solution :
private string GetPathToImage(Android.Net.Uri uri)
{
string doc_id = "";
using (var c1 = ContentResolver.Query(uri, null, null, null, null))
{
c1.MoveToFirst();
string document_id = c1.GetString(0);
doc_id = document_id.Substring(document_id.LastIndexOf(":") + 1);
}
string path = null;
// The projection contains the columns we want to return in our query.
string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
using (var cursor = ContentResolver.Query(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { doc_id }, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
When you choose a picture from gallery :
ChoosePhoto();
...
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
{
var uri = data.Data;
var path = GetPathToImage(uri);
System.Diagnostics.Debug.WriteLine("Image path == " + path );
//My result is this ==> [0:] Image path == /storage/emulated/0/DCIM/Camera/IMG_20170813_223324.jpg
}
}
Most important, when you use this method, maybe you will come across this problem :
Java.Lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=21975, uid=10417 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
When API >= 23, Requesting Permissions at Run Time, users grant permissions to apps while the app is running, not when they install the app. You should check if you have android.permission.READ_EXTERNAL_STORAGE
permission, if not, you need to request the permissions.