Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以Xamarin表单从图库中获取并显示所选照片的路径_Xamarin_Xamarin.forms_Xamarin.android_Xamarin.ios - Fatal编程技术网

以Xamarin表单从图库中获取并显示所选照片的路径

以Xamarin表单从图库中获取并显示所选照片的路径,xamarin,xamarin.forms,xamarin.android,xamarin.ios,Xamarin,Xamarin.forms,Xamarin.android,Xamarin.ios,我正在使用依赖服务从图库中挑选照片。我想在标签中显示用户从手机中选择图像时的路径 我读了太多日志,但没有得到正确的结果。 我想要这样: 现在所选图像已正确显示,但我不知道如何显示所选图像的路径 请建议我如何在android和ios上都这么做 注意:我正在使用依赖服务,所以我不想要第三方插件 我希望我能找到更好的解决方案。 提前感谢。在表单中创建界面 名称空间xxx { 公共接口IPhotoPickerService { 任务GetImageStreamAsync(); } } 在iOS中 [

我正在使用依赖服务从图库中挑选照片。我想在标签中显示用户从手机中选择图像时的路径

我读了太多日志,但没有得到正确的结果。 我想要这样:

现在所选图像已正确显示,但我不知道如何显示所选图像的路径

请建议我如何在android和ios上都这么做

注意:我正在使用依赖服务,所以我不想要第三方插件

我希望我能找到更好的解决方案。 提前感谢。

在表单中创建界面
名称空间xxx
{
公共接口IPhotoPickerService
{
任务GetImageStreamAsync();
}
}
在iOS中
[程序集:依赖项(typeof(PhotoPickerService))]
命名空间xxx.iOS
{
公共类PhotoPickerService:IPhotoPickerService
{
TaskCompletionSource TaskCompletionSource;
UIImagePicker控制器imagePicker;
任务IPhotoPickerService.GetImageStreamAsync()
{
//创建和定义UIImagePickerController
imagePicker=新UIImagePickerController
{
SourceType=UIImagePickerControllerSourceType.PhotoLibrary,
MediaTypes=UIImagePickerController.AvailableMediaTypes(UIImagePickerController源类型.PhotoLibrary)
};
//设置事件处理程序
imagePicker.FinishedPickingMedia+=OnImagePickerFinishedPickingMedia;
imagePicker.Cancelled+=OnImagePickerCancelled;
//当前UIImagePickerController;
UIWindow window=UIApplication.SharedApplication.KeyWindow;
var viewController=window.RootViewController;
viewController.PresentModalViewController(imagePicker,true);
//返回任务对象
taskCompletionSource=新的taskCompletionSource();
返回taskCompletionSource.Task;
}
无效OnImagePickerFinishedPickingMedia(对象发送方,UIImagePickerDipickeDeventargs参数)
{
UIImage image=args.EditedImage??args.OriginalImage;
如果(图像!=null)
{
//将UIImage转换为.NET流对象
国家统计局数据;
if(args.ReferenceUrl.PathExtension.Equals(“PNG”)| | args.ReferenceUrl.PathExtension.Equals(“PNG”))
{
data=image.AsPNG();
}
其他的
{
数据=image.AsJPEG(1);
}
Stream=data.AsStream();
取消注册EventHandlers();
Dictionary dic=新字典();
添加(args.ImageUrl.ToString(),流);
//将流设置为任务的完成
taskCompletionSource.SetResult(dic);
}
其他的
{
取消注册EventHandlers();
taskCompletionSource.SetResult(空);
}
imagePicker.DismissModalViewController(真);
}
void OnImagePickerCancelled(对象发送方、事件args args)
{
取消注册EventHandlers();
taskCompletionSource.SetResult(空);
imagePicker.DismissModalViewController(真);
}
void UnregisterEventHandlers()
{
imagePicker.FinishedPickingMedia-=OnImagePickerFinishedPickingMedia;
imagePicker.Cancelled-=OnImagePickerCancelled;
}
}
}
在Android中 在主活动中

public class MainActivity : FormsAppCompatActivity
{
    ...
    // Field, property, and method for Picture Picker
    public static readonly int PickImageId = 1000;

    public TaskCompletionSource<Dictionary<string,Stream>> PickImageTaskCompletionSource { set; get; }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
    {
        base.OnActivityResult(requestCode, resultCode, intent);

        if (requestCode == PickImageId)
        {
            if ((resultCode == Result.Ok) && (intent != null))
            {
                Android.Net.Uri uri = intent.Data;
                Stream stream = ContentResolver.OpenInputStream(uri);

                Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
                dic.Add(uri.ToString(), stream);
                // Set the Stream as the completion of the Task
                PickImageTaskCompletionSource.SetResult(dic);
            }
            else
            {
                PickImageTaskCompletionSource.SetResult(null);
            }
        }
    }
}
public类main活动:formsappcompative活动
{
...
//图片选择器的字段、属性和方法
公共静态只读int-PickImageId=1000;
public TaskCompletionSource PickImageTaskCompletionSource{set;get;}
受保护的覆盖void OnActivityResult(int请求代码、结果代码、意图)
{
base.OnActivityResult(请求代码、结果代码、意图);
if(requestCode==PickImageId)
{
if((resultCode==Result.Ok)&&(intent!=null))
{
Android.Net.Uri=intent.Data;
Stream=ContentResolver.OpenInputStream(uri);
Dictionary dic=新字典();
添加(uri.ToString(),流);
//将流设置为任务的完成
PickImageTaskCompletionSource.SetResult(dic);
}
其他的
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
[程序集:依赖项(typeof(PhotoPickerService))]
名称空间xxx.Droid
{
公共类PhotoPickerService:IPhotoPickerService
{
公共任务GetImageStreamAsync()
{
//定义获取图像的意图
意图=新意图();
intent.SetType(“image/*”);
intent.SetAction(intent.ActionGetContent);
//启动图片选择器活动(在MainActivity.cs中恢复)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(Intent,“选择图片”),
MainActivity.PickImageId);
//将TaskCompletionSource对象另存为MainActivity属性
MainActivity.Instance.PickImageTaskCompletionSource=新建TaskCompletionSource();
//返回任务对象
返回MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
调用它
Dictionary dic=wait DependencyService.Get().GetImageStreamAsync();
溪流;
字符串路径;
foreach(dic中的KeyValuePair currentImage)
{
stream=currentImage.Value;
path=currentImage.Key;
label.Text=路径;
if(流!=null)
{
图片
[assembly: Dependency (typeof (PhotoPickerService))]
namespace xxx.iOS
{
    public class PhotoPickerService : IPhotoPickerService
    {
        TaskCompletionSource<Dictionary<string, Stream>> taskCompletionSource;
        UIImagePickerController imagePicker;

        Task<Dictionary<string, Stream>> IPhotoPickerService.GetImageStreamAsync()
        {
            // Create and define UIImagePickerController
            imagePicker = new UIImagePickerController
            {
                SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
                MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
            };

            // Set event handlers
            imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
            imagePicker.Canceled += OnImagePickerCancelled;

            // Present UIImagePickerController;
            UIWindow window = UIApplication.SharedApplication.KeyWindow;
            var viewController = window.RootViewController;
            viewController.PresentModalViewController(imagePicker, true);

            // Return Task object
            taskCompletionSource = new TaskCompletionSource<Dictionary<string, Stream>>();
            return taskCompletionSource.Task;
        }

       

        void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            UIImage image = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data;
                if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
                {
                    data = image.AsPNG();
                }
                else
                {
                    data = image.AsJPEG(1);
                }
                Stream stream = data.AsStream();

                UnregisterEventHandlers();

                Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
                dic.Add(args.ImageUrl.ToString(), stream);

                // Set the Stream as the completion of the Task
                taskCompletionSource.SetResult(dic);
            }
            else
            {
                UnregisterEventHandlers();
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissModalViewController(true);
        }

        void OnImagePickerCancelled(object sender, EventArgs args)
        {
            UnregisterEventHandlers();
            taskCompletionSource.SetResult(null);
            imagePicker.DismissModalViewController(true);
        }

        void UnregisterEventHandlers()
        {
            imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia;
            imagePicker.Canceled -= OnImagePickerCancelled;
        }

        
    }
}

public class MainActivity : FormsAppCompatActivity
{
    ...
    // Field, property, and method for Picture Picker
    public static readonly int PickImageId = 1000;

    public TaskCompletionSource<Dictionary<string,Stream>> PickImageTaskCompletionSource { set; get; }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
    {
        base.OnActivityResult(requestCode, resultCode, intent);

        if (requestCode == PickImageId)
        {
            if ((resultCode == Result.Ok) && (intent != null))
            {
                Android.Net.Uri uri = intent.Data;
                Stream stream = ContentResolver.OpenInputStream(uri);

                Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
                dic.Add(uri.ToString(), stream);
                // Set the Stream as the completion of the Task
                PickImageTaskCompletionSource.SetResult(dic);
            }
            else
            {
                PickImageTaskCompletionSource.SetResult(null);
            }
        }
    }
}
[assembly: Dependency(typeof(PhotoPickerService))]
namespace xxx.Droid
{
    public class PhotoPickerService : IPhotoPickerService
    {
        public Task<Dictionary<string,Stream>> GetImageStreamAsync()
        {
            // Define the Intent for getting images
            Intent intent = new Intent();
            intent.SetType("image/*");
            intent.SetAction(Intent.ActionGetContent);

            // Start the picture-picker activity (resumes in MainActivity.cs)
            MainActivity.Instance.StartActivityForResult(
                Intent.CreateChooser(intent, "Select Picture"),
                MainActivity.PickImageId);

            // Save the TaskCompletionSource object as a MainActivity property
            MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Dictionary<string,Stream>>();

            // Return Task object
            return MainActivity.Instance.PickImageTaskCompletionSource.Task;
        }
    }
}
Dictionary<string, Stream> dic = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();

Stream stream;
string path;

foreach ( KeyValuePair<string, Stream> currentImage in dic )
{
   stream = currentImage.Value;

   path = currentImage.Key;

   label.Text = path;

   if (stream != null)
   {
      image.Source = ImageSource.FromStream(() => stream);
   }
}
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(uri.Path, stream);