2017-08-14 111 views
0
 public Point PixelSearchPoint(Bitmap b, Color PixelColor, int Shade_Variation) 
    { 


     Color Pixel_Color = PixelColor; 

     Point Pixel_Coords = new Point(-1, -1); 
     using (Bitmap RegionIn_Bitmap = (Bitmap)b.Clone()) 
     { 
      BitmapData RegionIn_BitmapData = RegionIn_Bitmap.LockBits(new Rectangle(0, 0, RegionIn_Bitmap.Width, RegionIn_Bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 

      int[] Formatted_Color = new int[3] { Pixel_Color.B, Pixel_Color.G, Pixel_Color.R }; //bgr 

      unsafe 
      { 
       for (int y = 0; y < RegionIn_BitmapData.Height; y++) 
       { 
        byte* row = (byte*)RegionIn_BitmapData.Scan0 + (y * RegionIn_BitmapData.Stride); 

        for (int x = 0; x < RegionIn_BitmapData.Width; x++) 
        { 
         if (row[x * 3] >= (Formatted_Color[0] - Shade_Variation) & row[x * 3] <= (Formatted_Color[0] + Shade_Variation)) //blue 
         { 
          if (row[(x * 3) + 1] >= (Formatted_Color[1] - Shade_Variation) & row[(x * 3) + 1] <= (Formatted_Color[1] + Shade_Variation)) //green 
          { 
           if (row[(x * 3) + 2] >= (Formatted_Color[2] - Shade_Variation) & row[(x * 3) + 2] <= (Formatted_Color[2] + Shade_Variation)) //red 
           { 
            Pixel_Coords = new Point(x, y); 
            RegionIn_Bitmap.Dispose(); 
            goto End; 

           } 
          } 
         } 
        } 
       } 
      } 
     } 
     End: 
     b.Dispose(); 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     return Pixel_Coords; 
    } 

从位图的查找颜色代码CSHARP不安全的BitmapData存取存储器泄漏

using (Bitmap b = new Bitmap(NativeHelper.GetOriginalWinScreen(handle))) 
          { 


           Point p = PixelSearchPoint(b, c, 0); 
           if (p.X != -1 && p.Y != -1) 
           { 
            Logwrite(p.X + "/" + p.Y + " Click With" + c.ToString()); 
            chk = true; 
            ClickPos(p.X, p.Y); 
            notecomplete = true; 
            counttest++; 
           } 

           b.Dispose(); 

          } 

此代码存储器中,以便快速泄漏此代码搜索时访问的不安全方法 GC.Collect的和GC.WaitForPendingFinalizers();不工作在UnSafe方法?

  1. 使用GDI +捕捉这种方法不是理性MemoryLeak
  2. 使用的foreach使用不安全的方法< <内存泄漏2GB以上的内存,从颜色查找点,并保持调试行消息OutOfMemoryException异常

回答

0

如果你调用RegionIn_Bitmap.LockBits,你需要确保在处理之前调用UnlockBits。

+0

'Pixel_Coords = new Point(x,y); b.UnlockBits(RegionIn_BitmapData); b.Dispose(); RegionIn_Bitmap.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); 转到最后;'仍然没有工作.. – cherry

+0

真的很有帮助谢谢 – cherry