I am writing a C# WPF application, I am using the AForge library for video streaming. I wanted to deploy the application, because everything worked on the first pc.
Than I deployed it and on the other pc I get the following Error:
"Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher"
This is the source Code, I am calling it on every new Frame which I get from the WebCam
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 Method:
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;
}
Further code:
private BitmapImage _image;
public BitmapImage Image {
get => _image;
set
{
_image = value;
OnPropertyChanged();
}
}
The start of the camera:
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"/>
I also tried this out:
Dispatcher.CurrentDispatcher.Invoke(() => Image = ToBitmapImage(bitmap));