Reputation: 5550
There are many example or source code on converting byte[]
to Bitmap
but I'm not sure on how to show or bind at my view xaml
.
My convert function as below:
private Bitmap ConvertByteToBitmap(byte[] bmpByte)
{
ImageConverter converter = new ImageConverter();
return (Bitmap)converter.ConvertFrom(bmpByte);
}
Says I have 10 users and user object has photo variable which is byte[]
type.
Now I'm wondering on how to bind the converted byte[]
to image
tag and display them in grid at xaml
? Should I create another variable to store the converted image result to bind at xaml
?
For example:
UserObject:
- Name: Jane
- Photo: 0x0023347dgas83.....
- Name: Isaac
- Photo: 0x1023347ddffeas83.....
Normally bind Text at textbox
like
<TextBox Text="{Binding [someviewmodel].UserObject.Name}"/>
What about the way to bind the bitmap image?
Upvotes: 1
Views: 1462
Reputation: 33364
This works:
public class MyItem
{
private readonly byte[] _image;
...
public byte[] Image { get { return _image; } }
}
and then in XAML for example:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Image}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ImageSourceConverter
does all the conversion for you
Upvotes: 1
Reputation: 4030
You have to create a new variable. If you know the dimensions of the picture, you can try this:
Image image;
BitmapSource bitmapSource = BitmapSource.Create(width, height, dpiWidth, dpiHeight,PixelFormats.Brg32, null, byteArrayIn, width * PixelFormats.Brg32.BitsPerPixel / 8);
image.Source = bitmapSource;
You can also try this:
private BitmapImage CreateImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var stream = new MemoryStream(imageData))
{
stream.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = stream;
image.EndInit();
}
image.Freeze();
return image;
}
Upvotes: 0