图像源wpf中出现NullReference异常

时间:2015-03-12 14:13:46

标签: c# wpf image

我正在使用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);

NullReferenceException在presentationCore.dll中出现

2 个答案:

答案 0 :(得分:0)

尝试添加:

bitmap.CreateOption = BitmapCreateOptions.IgnoreImageCache

这里还有一些

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

答案 1 :(得分:0)

您收到此错误是因为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中使用此代码以避免类似的问题。