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.
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.
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: