WPF图像无法从内存中呈现

时间:2010-07-03 09:54:55

标签: c# wpf image xaml jpeg

我的应用程序中有一个数据类,它维护一组表示JPEG图像的字节数组。它被定义为:

private ArrayList FrameList = new ArrayList();

我的Image对象渲染空白页面时遇到了一些麻烦(并且花了很多时间来完成它)。当我插入带有2K内存中字节数组(byte x[] = { lots of hex values };)的空白图像时:

FrameList.Insert(currFrame, x);

然后使用以下命令在其上导入JPEG文件:

byte[] bytes = File.ReadAllBytes(fspec);
FrameList[currFrame] = bytes;

将数组正确读入内存并存储在ArrayList中(通过调试器确认)。

然而,我有一个获取图像的功能:

public BitmapImage getCurrPicture()
{
    MemoryStream strm;
    BitmapImage bmp = new BitmapImage();
    strm = new MemoryStream((byte[])FrameList[currFrame-1]);
    bmp.CacheOption = BitmapCacheOption.None;
    bmp.BeginInit();
    bmp.StreamSource = strm;
    bmp.EndInit();
    strm.Close();
    return bmp;
}

被称为:

imgPicB.Source = data.getCurrPicture();

并且它并不总是呈现。

imgPicB在我的XAML中定义为:

<Image x:Name="imgPicB"
       Width="400"
       Height="300"
       Stretch="Fill"
       VerticalAlignment="Top" />

有趣的是,如果我使用完全相同的JPEG设置源来直接将源设置为文件URI,那么渲染就可以了。

在WPF中使用内存中JPEG图像有问题吗?从文件加载时是否有一些额外的智能(比如自动检测图像类型)?

2 个答案:

答案 0 :(得分:3)

试试这个:

public BitmapSource GetCurrPicture()
{
    var bitmapImage = new BitmapImage();
    using (Stream stream = new MemoryStream((byte[])FrameList[currFrame-1]))
    {
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
        bitmapImage.Freeze();
        return bitmapImage;
    }
}

这可以让WPF立即使用OnLoad解码图像,然后在完成后释放对流的引用。这意味着当流离开函数时,流可以被垃圾收集。否则,BitmapImage可以保留到流上,直到它被渲染。

在问题中发布的代码中,渲染会失败,因为:

  • 解码延迟;和
  • 流已在解码尝试发生的位置关闭。

答案 1 :(得分:1)

http://blogs.msdn.com/b/dwayneneed/archive/2008/06/20/implementing-a-custom-bitmapsource.aspx

DwayneNeed 2008年6月20日下午5:11 Comments

  • 缓存
    BitmapImage会将解码后的位图存储在系统内存中。您可以通过设置CacheOption属性来控制何时发生这种情况。 BitmapImage还维护以前BitmapImage实例的缓存(通过弱引用),以便多次加载相同的Uri将共享同一个实例。要避免此缓存,可以在BitmapCreateOptions.IgnoreImageCache属性中包含CreateOptions标志。