wpf 将内存流转换为 BitmapImage?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5346727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert memory stream to BitmapImage?
提问by David Veeneman
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.
我有一个最初是 PNG 的图像,我已将其转换为 byte[] 并保存在数据库中。最初,我只是将 PNG 读取到内存流中,然后将流转换为 byte[]。现在我想读回 byte[] 并将其转换为 BitmapImage,以便我可以将 WPF Image 控件绑定到它。
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.
我在网上看到很多相互矛盾和混乱的代码来完成将 byte[] 转换为 BitmapImage 的任务。由于图像最初是 PNG,我不确定是否需要添加任何代码。
How does one convert a stream to a BitmapImage?
如何将流转换为 BitmapImage?
回答by Patrick Klug
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 importantin this case because otherwise the BitmapImage might try to access the stream when loading on demand and the stream might already be closed.
这在这种情况下BitmapCacheOption.OnLoad
很重要,因为否则 BitmapImage 可能会在按需加载时尝试访问流,并且流可能已经关闭。
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.
您不必对图像格式做任何特殊处理 - BitmapImage 会处理它。
回答by Andreas
using (var stream = new MemoryStream(data))
{
var bi = BitmapFrame.Create(stream , BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
}