我正在从事一个使用 ONVIF 的闭路电视项目。我使用“ONVIF 设备管理器”项目提供的 Winform 示例从相机获取视频帧。(你可以在这里找到它)。我发现该示例使用 dispatcher.BeginInvoke() 在 UI 线程中放置了 CopyMemory() 块代码。我会减慢主 UI 线程,因为重复此块以在 PictureBox 中显示图像。
void InitPlayback(VideoBuffer videoBuffer, bool isInitial)
{
//....
var renderingTask = Task.Factory.StartNew(delegate
{
var statistics = PlaybackStatistics.Start(Restart, isInitial);
using (videoBuffer.Lock())
{
try
{
//start rendering loop
while (!cancellationToken.IsCancellationRequested)
{
using (var processingEvent = new ManualResetEventSlim(false))
{
var dispOp = disp.BeginInvoke((MethodInvoker)delegate
{
using (Disposable.Create(() => processingEvent.Set()))
{
if (!cancellationToken.IsCancellationRequested)
{
//update statisitc info
statistics.Update(videoBuffer);
//render farme to screen
//DrawFrame(bitmap, videoBuffer, statistics);
DrawFrame(videoBuffer, statistics);
}
}
});
processingEvent.Wait(cancellationToken);
}
cancellationToken.WaitHandle.WaitOne(renderinterval);
}
}
catch (OperationCanceledException error) { } catch (Exception error) { } finally { }
}
}, cancellationToken);
}
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, int count);
private void DrawFrame(VideoBuffer videoBuffer, PlaybackStatistics statistics)
{
Bitmap bmp = img as Bitmap;
BitmapData bd = null;
try
{
bd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);//bgra32
using (var md = videoBuffer.Lock())
{
CopyMemory(bd.Scan0, md.value.scan0Ptr, videoBuff.stride * videoBuff.height);
//bitmap.WritePixels(
// new Int32Rect(0, 0, videoBuffer.width, videoBuffer.height),
// md.value.scan0Ptr, videoBuffer.size, videoBuffer.stride,
// 0, 0
//);
}
}
catch (Exception err)
{
//errBox.Text = err.Message;
Debug.Print("DrawFrame:: " + err.Message);
}
finally
{
bmp.UnlockBits(bd);
}
imageBox.Image = bmp;
// var dispOp = disp.BeginInvoke((MethodInvoker)delegate {imageBox.Image = bmp;}); =>>Bitmap is already locked
}
我试图通过在UnlockBits()位图之后调用BeginInvoke()来排除UI 线程之外的CopyMemory()语句。但是,会引发错误“位图已锁定”。有一个问题已发布,我已按照该问题的答案进行操作,但在重绘 imageBox 时出现另一个错误“参数无效”。我猜如果我们锁定位图lock(bmp) {CopyMemory();...} imageBox 无法获取与其关联的位图信息。
非常感谢任何帮助。
更新建议的解决方案
private void DrawFrame(PlaybackStatistics statistics)
{
Bitmap bmp = new Bitmap(videoBuff.width, videoBuff.height);//img as Bitmap;
//...
imageBox.Invoke((MethodInvoker)delegate
{
Image bmTemp = imageBox.Image;
imageBox.Image = bmp;
if (bmTemp != null)
{
bmTemp.Dispose();
}
});
}