PngBitmapDecoder stream question
Don't know a whole lot about streams. Why does the first version work using a file but the second does not? Putting a breakpoint on "return dest;" it looks like both have created exactly the same thing but dest is always a blank image using the second version.
public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes, ImageFormat formatOfImage)
{
BitmapSource dest = null;
if (formatOfImage == ImageFormat.Png)
{
var streamOut = new FileStream("tmp.png", FileMode.Create);
streamOut.Write(imageBytes, 0, imageBytes.Length);
streamOut.Close();
Uri myUri = new Uri("tmp.png", UriKind.RelativeOrAbsolute);
var bdecoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
dest = bdecoder2.Frames[0];
}
return dest;
}
public static BitmapSource ConvertByteArrayToBitmapSource_NoWork(Byte[] imageBytes, ImageFormat formatOfImage)
{
BitmapSource des开发者_如何学Ct = null;
using (var stream = new MemoryStream(imageBytes))
{
var bdecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
stream.Flush();
dest = bdecoder.Frames[0];
stream.Close();
}
return dest;
}
You have to specify BitmapCacheOption.OnLoad
as the bitmap will otherwise be loaded when its displayed for the first time. Then, however, the stream is already disposed.
Also, take at look at this version supporting different image formats and freezing the image for better performance:
public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes)
{
using (MemoryStream stream = new MemoryStream(imageBytes))
{
BitmapDecoder deconder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
BitmapFrame frame = deconder.Frames.First();
frame.Freeze();
return frame;
}
}
精彩评论