创建 BitmapImage 抛出缺少键异常

问题描述 投票:0回答:3

我有一个视图,显示图像及其标题和旁边的评论。 当我加载现有图像时,我使用此代码:

        this.ArtifactIdentity = image.ArtifactIdentity;
        this.Comment = image.Comment;
        this.Name = image.Name;
        this.MediaIdentity = image.MediaIdentity;
        this.ImageArray = image.Image;
        Image = new BitmapImage();
        Image.BeginInit();
        Image.CacheOption = BitmapCacheOption.None;
        Image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        Image.StreamSource = new MemoryStream(this.ImageArray);
        Image.EndInit();

当我执行 EndInit() 时,它会抛出缺少参数键的异常。堆栈跟踪显示了这一点:

  at System.Collections.Hashtable.ContainsKey(Object key)
  at System.Collections.Hashtable.Contains(Object key)
  at System.Windows.Media.Imaging.ImagingCache.RemoveFromCache(Uri uri, Hashtable table)
  at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
  at System.Windows.Media.Imaging.BitmapImage.EndInit()

那么谁能告诉我为什么当我使用我已经看到许多其他人成功使用的代码时会出现此异常,但我却出现此异常???我迷茫了!

wpf c#-4.0
3个回答
12
投票

这是由 WPF 中的错误引起的,在

BitmapImage.FinalizeCreation()
:

if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
{
    ImagingCache.RemoveFromImageCache(uri); 
}

如果您指定

IgnoreImageCache
,但不从 URI 加载,则会中断。

去掉那个标志即可;它仅适用于从 URL 加载时。


1
投票

我发现了 Bradley Grainger here 撰写的一篇文章,其中列出了加载 BitmapImage 引起的异常。 SLaks 所说的是正确的,但在 Brad 的文章中,他指出下一个异常(没有适合完成的成像组件...)经常出现在 Windows 7 计算机上。该异常表明元数据以某种方式损坏。

我的解决方案进行了一些测试来确认,但基本上,如果我获取字节流,将其保存到临时文件,然后使用该临时文件填充 BitmapImage,我可以毫无例外地成功加载它。

这不是最理想的解决方案,但它做了我需要的一件事:它毫无例外地显示图像!


0
投票

重新读取时,始终确保您的流从 Position = 0 开始

© www.soinside.com 2019 - 2024. All rights reserved.