从MemoryStream png,gif创建WPF BitmapImage [英] Creating WPF BitmapImage from MemoryStream png, gif

查看:295
本文介绍了从MemoryStream png,gif创建WPF BitmapImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从Web请求获取的png和gif字节中从 MemoryStream 创建 BitmapImage 时遇到一些问题。这些字节似乎可以很好地下载,并且 BitmapImage 对象的创建没有问题,但是图像实际上并没有在我的UI上呈现。只有在下载的图像是png或gif类型时才会出现此问题(适用于jpeg)。

I am having some trouble creating a BitmapImage from a MemoryStream from png and gif bytes obtained from a web request. The bytes seem to be downloaded fine and the BitmapImage object is created without issue however the image is not actually rendering on my UI. The problem only occurs when the downloaded image is of type png or gif (works fine for jpeg).

以下是演示此问题的代码:

Here is code that demonstrates the problem:

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请求是否正确获取字节我尝试了以下哪个将字节保存到磁盘上的文件,然后使用 UriSource 而不是 StreamSource 加载图像,它适用于所有图像类型:

To test that the web request was correctly obtaining the bytes I tried the following which saves the bytes to a file on disk and then loads the image using a UriSource rather than a StreamSource and it works for all image types:

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;
}

任何人都有光芒吗?

推荐答案

.BeginInit()之后直接添加 bi.CacheOption = BitmapCacheOption.OnLoad

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

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

Without this, BitmapImage uses lazy initialization by default and stream will be closed by then. In first example you try to read image from possibly garbage-collected closed or even disposed MemoryStream. Second example uses file, which is still available. Also, don't write

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

更好

using (MemoryStream byteStream = new MemoryStream(buffer))
{
   ...
}

这篇关于从MemoryStream png,gif创建WPF BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆