How to convert Byte [] to Image in Xamarin MVVM?

2

How to convert an array from bytes to Image to Xamarin ? I'm returning an image that is with the string type through a WebApi and therefore I need to make it appear in the Image component.

    
asked by anonymous 09.11.2016 / 14:16

1 answer

3

It would basically be:

Image image = new Image();
Stream stream = new MemoryStream(byteArray);    
image.Source = ImageSource.FromStream(() => {return stream; });

where byteArray would be the variable that corresponds to byte[] of your image.

According to Xamarin - Binding an image to a byte [] property on a model of the user response Casper Nybroe : p>

Code

public class ByteArrayToImageSourceConverter : IValueConverter
{
    public object Convert(object value, 
           Type targetType, 
           object parameter, 
           System.Globalization.CultureInfo culture)
    {
        ImageSource retSource = null;
        if (value != null)
        {
            byte[] imageAsBytes = (byte[])value;
            retSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
        }
        return retSource;
    }

    public object ConvertBack(object value, 
           Type targetType, 
           object parameter, 
           System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Xaml

<ContentPage.Resources>
    <ResourceDictionary>
      <converters:ByteArrayToImageSourceConverter x:Key="ByteArrayToImage" />
    </ResourceDictionary>
</ContentPage.Resources>
<Image Source="{Binding SelectedPollItem.Image, 
                            Converter={StaticResource ByteArrayToImage}}" />

Reference:

09.11.2016 / 14:21