PngBitmapDecoder流问题
对流不太了解。为什么第一个版本可以使用文件工作,而第二个版本却不能?在“return dest;”上设置断点看起来两者都创建了完全相同的东西,但使用第二个版本的目标始终是空白图像。
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 dest = 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;
}
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 dest = 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须指定 BitmapCacheOption.OnLoad,否则位图将在首次显示时加载。然而,随后该流就已经被释放了。
另外,看看这个版本支持不同的图像格式并冻结图像以获得更好的性能:
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: