Hello everybody,
I needed a function to convert image data stored in byte array to a format, that can be displayed using some WPF controls. The byte array contains image data as is stored on harddisk, so there're also the header data. I've already had the code for System.Drawing.Image, which worked fine and I tried to write a WPF analogue to it.
Currently, I have this:
public static BitmapImage ToBitmapImage(this byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
BitmapImage img = new BitmapImage();
img.CacheOption = BitmapCacheOption.OnLoad;
img.BeginInit();
img.StreamSource = ms;
img.EndInit();
if (img.CanFreeze)
{
img.Freeze();
}
return img;
}
}
BitmapImage bd = myimage.ToBitmapImage();
imgCtrl.Source = bd;
The problem is,that the image is not displayed. I've tried different CacheOptions, but it didn't help. Maybe it's just some little thing, but I've no idea what is that. Thank you in advance :).
Solution
In my case, only a little tweak was needed and the code worked. CacheOption should be set after BeginInit(), not before calling it.
public static BitmapImage ToBitmapImage(this byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = ms;
img.EndInit();
if (img.CanFreeze)
{
img.Freeze();
}
return img;
}
}