从MemoryStream png,gif创建WPF BitmapImage

Sim*_*Fox 28 wpf memorystream image webrequest bitmapimage

我在创建一个BitmapImage来自MemoryStreamweb请求的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;
}
Run Code Online (Sandbox Code Playgroud)

为了测试Web请求是否正确获取字节,我尝试了以下操作,将字节保存到磁盘上的文件,然后使用a UriSource而不是a 加载图像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;
}
Run Code Online (Sandbox Code Playgroud)

有人发光吗?

alx*_*lxx 50

bi.CacheOption = BitmapCacheOption.OnLoad在你的后面直接添加.BeginInit():

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
...
Run Code Online (Sandbox Code Playgroud)

如果没有这个,BitmapImage默认使用延迟初始化,然后流将关闭.在第一个示例中,您尝试从可能是垃圾收集的封闭或甚至处置的MemoryStream中读取图像.第二个示例使用仍然可用的文件.另外,不要写

var byteStream = new System.IO.MemoryStream(buffer);
Run Code Online (Sandbox Code Playgroud)

更好

using (MemoryStream byteStream = new MemoryStream(buffer))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

  • `BitmapCacheOption.OnLoad`技巧很重要.我想补充说它应该在`BeginInit()`和`EndInit()`之间. (6认同)

Ale*_*ger 11

我正在使用此代码:

public static BitmapImage GetBitmapImage(byte[] imageBytes)
{
   var bitmapImage = new BitmapImage();
   bitmapImage.BeginInit();
   bitmapImage.StreamSource = new MemoryStream(imageBytes);
   bitmapImage.EndInit();
   return bitmapImage;
}
Run Code Online (Sandbox Code Playgroud)

可能你应该删除这一行:

bi.DecodePixelWidth = 30;
Run Code Online (Sandbox Code Playgroud)