简体   繁体   中英

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. 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. Don't forget to add the relevant permissions on android and iOS platform.

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 = 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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