Image source showing nothing when setting the source from a byte[] Xamarin Forms

coldstarjoey 1 Reputation point
2021-03-23T13:05:26.707+00:00

Hi all I have a byte[] which I save from the Xamarin Essentials Media Picker, I want to display the image on my XAML page so all I have is a blank XAML page with a StackLayout and in my code I do the following:

Stream stream = new MemoryStream(filebyte);
            var imageSource = ImageSource.FromStream(() => stream);

            Image test = new Image();

            test.Source = imageSource;

            test.WidthRequest = 50;
            test.HeightRequest = 50;

            ImageStack.Children.Add(test);

but when the page loads nothing is there. i'm I missing something

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,297 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-03-24T08:44:00.74+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    Here is a sample which is implemented by Xamarin.Essentials: Media Picker.

    You can refer to the following code:

        async void Button_Clicked(System.Object sender, System.EventArgs e)  
        {  
            var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions  
            {  
                Title = "Please pick a photo"  
            });  
    
            if (result != null)  
            {  
                var stream = await result.OpenReadAsync();  
    
                resultImage.Source = ImageSource.FromStream(() => stream);  
            }  
        }  
    

    The xaml code:

    <Image x:Name="resultImage" />  
    

    And you can check the full sample here: https://github.com/jfversluis/XFEMediaPickerSample

    Update:

    We just need to use the following code, the rest can be deleted(I tested on my side, it works properly.):

        async Task LoadPhotoAsync(FileResult photo)  
        {  
            // canceled  
            if (photo == null)  
            {  
                PhotoPath = null;  
                return;  
            }  
            // save the file into local storage  
            var newFile = photo.FullPath;  
    
            var stream = await photo.OpenReadAsync();  
    
            MyImage.Source = ImageSource.FromStream(() => stream);  
        }  
    }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.