我正试图获得Gallery Image的路径。我得到的图像路径存储在内部存储器中,但不存储在外部存储器中。我还启用了已授予的读写存储和摄像头访问权限。 这是我的代码
void ChoosePhoto()
{
try
{
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), 0);
}
catch (Exception ex)
{
throw ex;
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE)
{
// camera operation
}
else
{
Console.WriteLine("choose pic from Gallery");
var uri = data.Data;
var path = getRealPathFromURI(uri); //path returns null when i select image from external storage;
}
}
private String getRealPathFromURI(Uri contentURI)
{
string[] proj = { MediaStore.Images.ImageColumns.Data };
String result;
var cursor = ContentResolver.Query(contentURI, proj, null, null, null);
if (cursor == null)
result = contentURI.Path;
else
{
int idx= cursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
result = cursor.GetString(idx);
cursor.Close();
}
return result;
}
答案 0 :(得分:4)
我想获取我从图库中选择的所选图像路径
问题是将Android.Net.Uri
更改为path
,这是一个解决方案:
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;
}
当您从图库中选择图片时:
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
}
}
最重要的,当您使用此方法时,您可能会遇到此问题:
Java.Lang.SecurityException:Permission Denial:从pid = 21975读取com.android.providers.media.MediaProvider uri content:// media / external / images / media,uid = 10417需要android.permission.READ_EXTERNAL_STORAGE,或者grantUriPermission()
当API> = 23,Requesting Permissions at Run Time时,用户会在应用运行时向应用授予权限,而不是在安装应用时授予权限。您应该检查您是否拥有android.permission.READ_EXTERNAL_STORAGE
权限,否则,您需要申请权限。