2012-12-12 71 views
0

我使用以下代碼從某個像素位置獲取RGB顏色。比較像素圖表

public Color GetColorAt(Point location) 
{ 
    using (Graphics gdest = Graphics.FromImage(screenPixel)) 
    { 
     using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero)) 
     { 
      IntPtr hSrcDC = gsrc.GetHdc(); 
      IntPtr hDC = gdest.GetHdc(); 
      int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy); 
      gdest.ReleaseHdc(); 
      gsrc.ReleaseHdc(); 
     } 
    } 

    return screenPixel.GetPixel(0, 0); 
} 

但是,有什麼辦法可以保存圖表,例如10x10像素?我的目標是將一張圖表與另一張圖表進行比較,看看它們是否相同。

回答

1

您可以創建一個方法拷貝屏幕的一部分到你想要的任何大小的Bitmap(假設你沒有創建位圖不是在這種情況下,你應該檢查大小的屏幕大)像例如:

public Bitmap GetPartOfTheScreen(Point location, Size size) 
{ 
    Bitmap screenPartCopy = new Bitmap(size.Width, size.Height); 
    using (Graphics gdest = Graphics.FromImage(screenPartCopy)) 
    { 
     using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero)) 
     { 
      IntPtr hSrcDC = gsrc.GetHdc(); 
      IntPtr hDC = gdest.GetHdc(); 
      int retval = BitBlt(hDC, 0, 0, size.Width, size.Height, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy); 
      gdest.ReleaseHdc(); 
      gsrc.ReleaseHdc(); 
     } 
    } 

    return screenPartCopy; 
} 

當你在屏幕的部分,你可以通過使用GetPixel(慢的方法)比較像素顏色或者你可以採取Bitmap類的LockBits方法的優勢,像素比較。

+0

謝謝,看起來就像我需要的東西! – Johan

+0

沒問題,很高興我能幫上忙。 –