我正在编写一个C# WPF应用程序,我正在使用AForge库的视频流。我想部署的应用程序,因为一切工作在第一台PC。
比我部署它,并在其他PC上,我得到以下错误。
"Must create DependencySource on the same Thread as the DependencyObject even by using Dispatcher" "必须在与DependencyObject相同的线程上创建依赖源,即使使用Dispatcher"
这是源码,我在从WebCam获得的每一个新的Frame上调用它。
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{ if (StreamRunning) { try { using (var bitmap = (Bitmap)eventArgs.Frame.Clone()) {
Image = ToBitmapImage(bitmap);
}
Image.Freeze();
}
catch (Exception e)
{
UIMessages = "Error: NewFrame " + e.Message;
}
}
}
ToBitmapImage方法。
private BitmapImage ToBitmapImage(Bitmap bitmap)
{
var start = 420;
var end = 1920 - 2* 420;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
Bitmap source = bitmap;
Bitmap CroppedImage = source.Clone(new System.Drawing.Rectangle(start, 0, end, 1080), source.PixelFormat);
CroppedImage.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
进一步的代码:
private BitmapImage _image;
public BitmapImage Image {
get => _image;
set
{
_image = value;
OnPropertyChanged();
}
}
摄像机的开始。
if (SelectedDevice != null)
{
_videoSource = new VideoCaptureDevice(SelectedDevice.MonikerString);
//var test = _videoSource.VideoCapabilities;
_videoSource.NewFrame += video_NewFrame;
_videoSource.Start();
}
UI:
<Image Height="400" Width="400" Source="{Binding Image, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,0"/>
我也试了一下
Dispatcher.CurrentDispatcher.Invoke(() => Image = ToBitmapImage(bitmap));
当从流中加载一个BitmapImage时,你通常会尽快关闭流,并确保BitmapImage被立即加载,通过设置 "加载BitmapImage "来实现。BitmapCacheOption.OnLoad
.
private static BitmapImage ToBitmapImage(Bitmap bitmap)
{
var start = 420;
var end = 1920 - 2 * 420;
var croppedBitmap = bitmap.Clone(
new System.Drawing.Rectangle(start, 0, end, 1080),
bitmap.PixelFormat);
var bi = new BitmapImage();
using (var ms = new MemoryStream())
{
croppedBitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = ms;
bi.EndInit();
}
bi.Freeze();
return bi;
}