我一直在嘗試在網上找到多種解決方案,並且尚未找到可用的解決方案。Xamarin Android - 從圖庫中選擇圖片並獲取路徑
我試圖從圖庫中選擇一個圖像,然後上傳它。現在,我只是想弄清楚如何獲得圖像的路徑。
我首先嚐試了配方,發現here,但是,總是返回null作爲答案。
我現在試圖使用這個代碼,我從另一個SO問題中找到。
public static readonly int ImageId = 1000;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
GetImage(((b, p) => {
Toast.MakeText(this, "Found path: " + p, ToastLength.Long).Show();
}));
}
public delegate void OnImageResultHandler(bool success, string imagePath);
protected OnImageResultHandler _imagePickerCallback;
public void GetImage(OnImageResultHandler callback)
{
if (callback == null) {
throw new ArgumentException ("OnImageResultHandler callback cannot be null.");
}
_imagePickerCallback = callback;
InitializeMediaPicker();
}
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) {
return;
}
string imagePath = null;
var uri = data.Data;
try {
imagePath = GetPathToImage(uri);
} catch (Exception ex) {
// Failed for some reason.
}
_imagePickerCallback (imagePath != null, imagePath);
}
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 = ManagedQuery(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;
}
但是,路徑仍爲空。
如何獲取所選圖像的路徑?
這就是我鏈接的食譜說要做的事情。這也返回null。 – Gavin