【问题标题】:NullReference Exception Occurs in Image Source wpf图像源 wpf 中出现 NullReference 异常
【发布时间】:2015-03-12 14:13:46
【问题描述】:

我正在使用 FileSystemWatcher 从我的 Assets 文件夹中获取最新图像,我有一个网络摄像头来捕获图像并将其保存在 Assets 文件夹中。保存图像后,我从 FileSystemWatcher 事件中获取最新图像。 这是我的代码:

 //FileWatcher
 private void FileWatcher()
    {
        path = @"..\..\Assets\WebCamImage\";
        System.IO.FileSystemWatcher watcher = new FileSystemWatcher(path);
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;

        watcher.Changed += watcher_Changed;
        watcher.EnableRaisingEvents = true;
    }


 //Event
 void watcher_Changed(object sender, FileSystemEventArgs e)
    {                 
      CustomerImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(
        delegate()
        {                     
       CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);
        }
        ));
    }    

在页面加载事件中,CustomerImage 控件的源设置为默认图片 nopictureavail.jpeg,当在该特定目录中进行更改时,图像应填充到 CustomerImage 中,filewatcher 事件触发,然后在

CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);

在presentationCore.dll中发生NullReferenceException

【问题讨论】:

    标签: c# wpf image


    【解决方案1】:

    尝试添加这个:

    bitmap.CreateOption = BitmapCreateOptions.IgnoreImageCache
    

    这里还有一些

    https://stackoverflow.com/a/1689808/2609288

    【讨论】:

    • 我已经更改了我的代码,以前的代码不起作用,请仔细阅读编辑过的代码并给我一些建议。
    【解决方案2】:

    您收到此错误是因为 WPF 保留了其图像的句柄。尝试改用此代码:

    BitmapImage image = new BitmapImage();
    try
    {
        using (FileStream stream = File.OpenRead(filePath))
        {
            image.BeginInit();
            image.StreamSource = stream;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.EndInit();
        }
    }
    catch { return DependencyProperty.UnsetValue; }
    

    我在IValueConverter 中有这段代码以避免类似的问题。

    【讨论】:

    • 你问了一个问题,我回答了。你真的不应该在回答后改变你的问题来问另一个问题。如果您还有其他问题,那么您应该提出一个新问题,如果您想提供一些上下文,则可能提供指向原始问题的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多