32

我在从 web 请求获得的 png 和 gif 字节创建一个时遇到了一些BitmapImage麻烦MemoryStream。字节似乎下载得很好,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 请求是否正确获取字节,我尝试了以下操作,将字节保存到磁盘上的文件中,然后使用 aUriSource而不是 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;
}

有没有人可以发光?

4

2 回答 2

51

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

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
...

如果没有这个,BitmapImage 默认使用延迟初始化,届时流将被关闭。在第一个示例中,您尝试从可能被垃圾收集的已关闭甚至已处置的 MemoryStream 中读取图像。第二个示例使用文件,该文件仍然可用。还有,不要写

var byteStream = new System.IO.MemoryStream(buffer);

更好的

using (MemoryStream byteStream = new MemoryStream(buffer))
{
   ...
}
于 2010-02-12T09:45:47.747 回答
13

我正在使用这段代码:

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

也许你应该删除这一行:

bi.DecodePixelWidth = 30;
于 2010-01-20T00:07:38.020 回答