2012-07-02 34 views
0

我想捕捉從C#中的AForge.Net攝像頭幀。不幸的是,我在_CurrentFrame.LockBits上得到了一個ArgumentException。我想我的事件寫入鎖定的位圖有問題!?有時我還會在UnlockBits中得到「GDI +中發生的一般錯誤」。事件訪問位圖,而其鎖定

public bool GetFrame(ref Draw.STexture Frame) 
{ 
    BitmapData bd = _CurrentFrame.LockBits(new Rectangle(0, 0, _CurrentFrame.Width, _CurrentFrame.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
    byte[] data = new byte[4 * _CurrentFrame.Width * _CurrentFrame.Height]; 
    Marshal.Copy(bd.Scan0, data, 0, data.Length); 
    //Do something with data here 
    _CurrentFrame.UnlockBits(bd); 
    _CurrentFrame.Dispose(); 
} 

private void OnFrame(object sender, NewFrameEventArgs e) 
{ 
    if (_CurrentFrame != null) 
     _CurrentFrame.Dispose(); 
    _CurrentFrame = (Bitmap)e.Frame.Clone(); 
} 

回答

0

Bitmap.Clone()方法很危險,它會創建位圖的淺表副本。該副本將指針存儲到像素數據,而不是複製像素。在大多數相機驅動程序中,該指針僅在回調(事件)運行時有效。如果您稍後嘗試使用它,那麼您將訪問無效的像素數據,極有可能在LockBits上發生異常。

要麼處理而要麼事件運行或使用Bitmap(Image)構造函數創建深層副本。當然,該副本往往很昂貴。