I'm working with Xamarin Forms and I want to load a listview with imagecells, also I'm binding the data with XAML.
My webservice provider returns me the binary code of the images, ¿someone knows how I can convert this to show the image?
This is my XAML listview template:
<ListView x:Name="lv_products">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell
Text="{Binding Name}"
Detail="{Binding Description}"
ImageSource="{Binding Image, Converter={StaticResource cnvImage}}">
</ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And the converter:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value is byte[])
{
byte[] binary = (byte[])value;
Image image = new Image();
image.Source = ImageSource.FromStream(() => new MemoryStream(binary));
return image.Source;
}
return null;
}
But picture appears empty (transparent).
Here is working converter. I use MemoryStream and ImageSource.FromStream.
public class ByteImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var image = value as byte[];
if (image == null)
return null;
return ImageSource.FromStream(() => new MemoryStream(image));
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Just as sample here is my page
public partial class Page : ContentPage
{
readonly ViewModel _bindingContext = new ViewModel();
public Page()
{
InitializeComponent();
BindingContext = _bindingContext;
LoadImage();
}
private async void LoadImage()
{
var assembly = typeof (ByteImageConverter).GetTypeInfo().Assembly;
var stream = assembly
.GetManifestResourceStream("TestImage.c5qdlJqrb04.jpg");
using (var ms = new MemoryStream())
{
await stream.CopyToAsync(ms);
_bindingContext.Image = ms.ToArray();
}
}
}
public class ViewModel : INotifyPropertyChanged
{
private byte[] _image;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(
[CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public byte[] Image
{
get { return _image; }
set
{
_image = value;
OnPropertyChanged();
}
}
}
If you have a URL which returns the image file, why aren't you just use the URL as ImageSource ?
<ImageCell Text="{Binding Name}"
Detail="{Binding Description}"
ImageSource="{Binding ImageURL}">
</ImageCell>
You can convert byte array to Bitmap image, and assign that bitmap to the ImageView. I did this in Xamarin.Android, dnt know will it work with forms or not.
bitmap = BitmapFactory.DecodeByteArray(byte, 0, byte.Length);
Then use imageView.FromBitmap() to display this image.