简体   繁体   English

Xamarin forms 显示图像问题

[英]Xamarin forms display an image issue

I use a photo picker to let the user choose a profile pic and then I want to display the pic inside of an Image view.我使用照片选择器让用户选择个人资料照片,然后我想在图像视图中显示照片。 the following code works fine for me but then I would like to convert the image to a byte array, once I call the method to convert it the image doesn't display after the user picks it.以下代码对我来说很好,但是我想将图像转换为字节数组,一旦我调用转换它的方法,图像在用户选择后不会显示。 I also tried to call the method outside the try and catch but no luck.我还尝试在 try and catch 之外调用该方法,但没有运气。 the image is getting selected (it's getting saved in local storage) so the only issue is that for some reason it doesn't display it in the view.图像被选中(它被保存在本地存储中)所以唯一的问题是由于某种原因它没有在视图中显示。

  async void showMediaPicker()
            {
                var res = await MediaPicker.PickPhotoAsync();
                try
                {
                    var stream = await res.OpenReadAsync();
                    var finalImage = ImageSource.FromStream(() => stream);
                    myImage.Source = finalImage;
                    imgBytes = ImageSourceToBytes(finalImage);

                }
                catch (Exception e)
                {
                  Console.Write("error" + e.Message) ;
                }

            }

If you want to convert the photo to Byte array, you could use the plugin Media.Plugin from Nuget to pick or take photo.如果要将照片转换为字节数组,可以使用 Nuget 中的插件Media.Plugin来挑选或拍照。 Don't forget to add the relevant permissions on android and iOS platform.不要忘记在android和iOS平台上添加相关权限。

await CrossMedia.Current.Initialize();
    
    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
        DisplayAlert("No Camera", ":( No camera available.", "OK");
        return;
    }

    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
        SaveToAlbum = true,
        Name = "test.jpg"
    });

    if (file == null)
        return;

Then convert it to Stream firstly before convert it to byte array.然后先将其转换为Stream ,然后再转换为字节数组。

 Stream stream = file.GetStream();
public byte[] GetImageStreamAsBytes(Stream input)
{
  var buffer = new byte[16*1024];
  using (MemoryStream ms = new MemoryStream())
  {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
                ms.Write(buffer, 0, read);
    }
      return ms.ToArray();
   }
}

Now you can get the byte array like following现在你可以得到如下的字节数组

var imgDate = GetImageStreamAsBytes(stream);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM