title: Unsafe C# bitmap floodfill
body: <p>**</p>
  
  <h2>How to make 'GetPixel2' work for finding the color at a point</h2>
  
  <p>**
  So I have a bitmap with lots of single colored shapes.
  I have a list of x,y points for those shapes. Then, a second list
  with the expected color at those points.</p>
  
  <p>Finally have an algorithm using bitmap.Getpixel and SetPixel working.
  Which was definitely slow. 
  <a href="http://csharpexamples.com/fast-image-processing-c/" rel="nofollow">http://csharpexamples.com/fast-image-processing-c/</a>
  Suggests using direct memory access to solve this. I'd like to use their sample without looping through the entire image, and hit a single x,y point.</p>
  
  <pre><code>Bitmap bmp2 = (Bitmap)Bitmap.FromFile(Environment.CurrentDirectory + @"\Content\map\provinces.bmp");
  BitmapData bitmapData = bmp2.LockBits(new System.Drawing.Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadWrite, bmp2.PixelFormat);
  int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(bmp2.PixelFormat) / 8;
  int heightInPixels = bitmapData.Height;
  int widthInBytes = bitmapData.Width * bytesPerPixel;
  System.Drawing.Point pt = new System.Drawing.Point((int)provpos2[0].X, (int)provpos2[0].Y);
  System.Drawing.Color targetColor = System.Drawing.Color.FromArgb(255, provcolors[0].R, provcolors[0].G, provcolors[0].B);
  if (!ColorMatch(GetPixel2(pt.X, pt.Y, bytesPerPixel, bitmapData), targetColor)){ 
      // This hits the completely wrong area.
  }
  
  
  public System.Drawing.Color GetPixel2(int x, int y, int bytesPerPixel, BitmapData bitmapData)
  {
      unsafe
      {
          byte* ptrFirstPixel = (byte*)bitmapData.Scan0;
          byte* currentLine = ptrFirstPixel + (y * bitmapData.Stride);
          x = x + bytesPerPixel;
          System.Drawing.Color a = System.Drawing.Color.FromArgb(255, currentLine[x + 2], currentLine[x + 1], currentLine[x]);
  
          return a;
      }
  }
  
  public static bool ColorMatch(System.Drawing.Color a,System.Drawing.Color b)
  {
  
      return (a.ToArgb() &amp; 0xffffff) == (b.ToArgb() &amp; 0xffffff);
  }
  </code></pre>
  
  <p>bytesPerPixel comes out at 3. Tried changing it to 4 just hits another undesired location on the bitmap.</p>
  
  <ul>
  <li>It seems to hit around 1023x,351y instead of the desired 3084x,319y on a 5632x2048 bitmap. </li>
  </ul>