从Memorystream PNG,GIF创建WPF位图像
-
21-09-2019 - |
题
我在创建一个 BitmapImage
来自 MemoryStream
从来自Web请求获得的PNG和GIF字节。字节似乎已下载正常, BitmapImage
对象是没有问题的,但是该图像实际上并未在我的UI上呈现。仅当下载的图像是PNG或GIF类型时才发生的问题(对JPEG工作正常)。
这是证明问题的代码:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
Byte[] buffer = new Byte[webResponse.ContentLength];
stream.Read(buffer, 0, buffer.Length);
var byteStream = new System.IO.MemoryStream(buffer);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 30;
bi.StreamSource = byteStream;
bi.EndInit();
byteStream.Close();
stream.Close();
return bi;
}
为了测试Web请求正确地获取字节,我尝试了以下内容,该字节将字节保存到磁盘上的文件,然后使用A加载图像 UriSource
而不是一个 StreamSource
它适用于所有图像类型:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
Byte[] buffer = new Byte[webResponse.ContentLength];
stream.Read(buffer, 0, buffer.Length);
string fName = "c:\\" + ((Uri)value).Segments.Last();
System.IO.File.WriteAllBytes(fName, buffer);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 30;
bi.UriSource = new Uri(fName);
bi.EndInit();
stream.Close();
return bi;
}
有人发光吗?
解决方案
添加 bi.CacheOption = BitmapCacheOption.OnLoad
直接在您之后 .BeginInit()
:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
...
没有此,Bitmapimage默认使用懒惰初始化,到那时将关闭流。在第一个示例中,您尝试从可能读取图像 垃圾收集 封闭甚至处置的内存线。第二个示例使用文件,该文件仍然可用。另外,不要写
var byteStream = new System.IO.MemoryStream(buffer);
更好的
using (MemoryStream byteStream = new MemoryStream(buffer))
{
...
}
其他提示
我正在使用此代码:
public static BitmapImage GetBitmapImage(byte[] imageBytes)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(imageBytes);
bitmapImage.EndInit();
return bitmapImage;
}
可能是您应该删除这一行:
bi.DecodePixelWidth = 30;
不隶属于 StackOverflow