I have this table, and want to get the data from it. It contains an image file that I saved as varbinary
datatype. I want to show the image in the datagrid as a description.
I have the following code for conversion from bytes to varbinary
(image) and from image to byte.
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
using (var stream = new MemoryStream())
{
var encoder = new PngBitmapEncoder(); // or some other encoder
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(stream);
return stream.ToArray();
}
}
public ImageSource BytesToImage(byte[] imageData)
{
using (var ms = new MemoryStream(imageData))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
ImageSource imgSrc = image as ImageSource;
return imgSrc;
}
}
The conversion from image to byte[]
works. But I'm not sure if the code for conversion from bytes to image works.
I also have a compile error in the linq query where I call the data from database:
public List<RoomViewModel> getRooms()
{
List<RoomViewModel> getRoomsQuery;
using (db = new MyHotelDBContext())
{
getRoomsQuery = (from r in db.Rooms
join t in db.RoomTypes on r.RoomTypeID equals t.ID
join f in db.Floors on r.FloorID equals f.ID
select new RoomViewModel
{
ID = r.ID,
Nr = r.Nr,
rType = t.Name,
Image = BytesToImage(r.Image as BitmapImage),
Description = r.Description,
rFloor = f.Floor1
}).ToList();
}
return getRoomsQuery ?? new List<RoomViewModel>();
}
Where is the problem with this line:
Image = BytesToImage(r.Image as BitmapImage)
How can I fix/improve this code?