Convert memory stream to BitmapImage?
I have an image that was originally a PNG that I have converted to a byte[] and saved in a database. Originally, I simply read the PNG into a memory stream and converted the stream into a byte[]. Now I want to read the byte[] back and convert it to a BitmapImage, so that I can bind a WPF Image control to it.
I am seeing a lot of contradictory and confusing code online to accomplish the task of converting a byte[] to a BitmapImage. I am not sure whether I need to add any code due to the fact that the image was originally a PNG.
How does one convert a stream to a BitmapImage?
This should do it:
using (var stream = new MemoryStream(data))
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
bitmap.Freeze();
}
The BitmapCacheOption.OnLoad
is important in this case because otherwise the BitmapImage might try to access the stream when loading on demand and the stream might already be closed.
Freezing the bitmap is optional but if you do freeze it you can share the bitmap across threads which is otherwise impossible.
You don't have to do anything special regarding the image format - the BitmapImage will deal with it.
using (var stream = new MemoryStream(data))
{
var bi = BitmapFrame.Create(stream , BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
}