如何从xamarin android中的库中获取所选图像名称。当USer点击按钮然后图库被打开并且我得到图像但我不知道如何获取图像名称。
当用户单击图像库打开的按钮并选择图像时,这是按钮单击事件
fab2.Click += (o, e) =>
{
Intent = new Intent(Intent.ActionPick,
MediaStore.Images.Media.InternalContentUri);
Intent.SetType("image/*");
StartActivityForResult(Intent.CreateChooser(Intent,"SelectPicture"), 1 );
};
选择图像后,我得到的图像,但是...这里有问题。我不知道如何获得所选的图像名称。
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Android.Net.Uri uri = data.Data;
string path = uri.Path;
string filename = path.Substring(path.LastIndexOf("/") + 1);
// String s = path(selectedImageUri);
Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
}
}
修改此代码添加方法Getpath(),它将返回所选图像的路径,您可以在其中获取所选图像的名称。
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
string imagePath = null;
Android.Net.Uri uri = data.Data;
var path = GetPath(uri);
string filename = path.Substring(path.LastIndexOf("/") + 1);
// String s = path(selectedImageUri);
Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
}
}
public string GetPath(Android.Net.Uri uri)
{
string path = null;
String[] projection = { MediaStore.MediaColumns.Data };
ContentResolver cr = ApplicationContext.ContentResolver;
var metaCursor = cr.Query(uri, projection, null, null, null);
if (metaCursor != null)
{
try
{
if (metaCursor.MoveToFirst())
{
path = metaCursor.GetString(0);
}
}
finally
{
metaCursor.Close();
}
}
return path;
}