System.Drawing.Image 를 System.Windows.Media.ImageSource 로 변환하는 함수
public static ImageSource ToImageSource(Image image, ImageFormat imageFormat)
{
using MemoryStream stream = new();
// Save to the stream
image.Save(stream, imageFormat);
// Rewind the stream
stream.Seek(0, SeekOrigin.Begin);
// Tell the WPF BitmapImage to use this streamtreeze
var BitmapImg = new BitmapImage();
BitmapImg.BeginInit();
BitmapImg.CacheOption = BitmapCacheOption.OnLoad;
BitmapImg.StreamSource = stream;
BitmapImg.EndInit();
return BitmapImg;
}
위 코드는 메인 스레드에서 이미지를 할당하는 것을 의도하신 것 같은데 첫 번째 BeginInvoke 부분에서 실수를 하신 것 같네요. 그래서 마지막 줄의 ImgCamView_Before[0].Source를 Set하는 코드가 메인 스레드와 카메라 프레임 수신 스레드에서 교차로 호출되고, 또 무한 반복되고 있는 듯 합니다.
그리고 Cam_OnFrameReceived 함수로 넘어오는 Image 객체에 대해서 Dispose()를 호출하지 않아도 되는지 확인이 필요할 것 같습니다. 이전 코드에서 BeginInvoke로 호출해서 잘 동작했다면 Cam 라이브러리가 Bitmap 리소스를 Release 하지 않을 가능성이 큽니다. 메모리 누수가 없는지 확인해보시고 메모리가 계속 증가한다면 ToImageSource함수에서 image.Save 후 image 객체를 Dispose하세요.
///////////////////////////////////////////////
BitmapImg.EndInit();
BitmapImg.Freeze(); //Important to freeze it, otherwise it will still have minor leaks
///////////////////////////////////////////////