空引用异常 - Takephotoasync xamarin

时间:2017-05-09 16:28:44

标签: xamarin.forms

我正在使用James Montemagno的媒体插件。我已经安装了插件并添加了所有必需的权限。但是,当我运行我的应用程序时,我在以下代码的第一行得到一个空引用异常:

image.Source = ImageSource.FromStream(() =>{var stream = file.GetStream();file.Dispose();return stream;});

我试着找了近2天的解决方案而没有运气! 非常感激任何的帮助! 提前谢谢!

2 个答案:

答案 0 :(得分:1)

我建议download the source

HERE您可以找到如何使用该插件的示例。

    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
      PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
      Directory = "Sample",
      Name = "test.jpg"
    });

    if (file == null)
      return;

    DisplayAlert("File Location", file.Path, "OK");

    image.Source = ImageSource.FromStream(() =>
    {
      var stream = file.GetStream();
      file.Dispose();
      return stream;
    });
  };

答案 1 :(得分:0)

我有同样的问题,因为ImageSource.FromStream总是释放创建的流...这是我的代码,它拍摄照片并在绑定的ListView中显示图片。

简而言之,我从插件中获取原始流,然后将其转换为byte []并将其存储在专用对象中。当我需要将图片显示到图像源时,我从byte []创建一个新流,并将其与Xamarin.Forms中的ImageSource.FromStream方法一起使用。

    public class PictureModel
    {
        public byte[] File { get; set; }
        public ImageSource ImageSource => ImageSource.FromStream(() => new MemoryStream(File));
    }

    public class PicturesViewModel : ViewModelBase
    {
        public ObservableCollection<PictureModel> Pictures { get; set; } = new ObservableCollection<PictureModel>();

        public ICommand TakePictureCommand => new Command(async () =>
        {
            var stream = await TakePictureAsync();
            var picture = new PictureModel { File = await ImageConverter.ReadFully(stream) }; // custom method to convert stream into byte[]
            Pictures.Add(picture);
        });

        protected async Task<Stream> TakePictureAsync()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                return null;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                SaveToAlbum = false,
                PhotoSize = PhotoSize.Medium
            });

            if (file == null)
                return null;

            var stream = file.GetStream();
            file.Dispose();
            return stream;
        }
    }
  

也许我需要在TakePictureCommand中处理本地流但是   我还没有测试过。

和XAML:

<ListView x:Name="listView" ItemsSource="{Binding Pictures}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" RowHeight="200">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Image Source="{Binding ImageSource}" WidthRequest="400" HeightRequest="200" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>