title: .Net getting RGB values from a bitmap using Lockbits
body: <p>I am using the below code to extract RGB values from images, sometimes this works, however on certain files (seemingly where the Stride is not divisible by the width of the bitmap) it is returning mixed up values: </p>
  
  <pre><code>Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
  Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadOnly, Imaging.PixelFormat.Format24bppRgb)
  Dim ptr As IntPtr = bmpData.Scan0
  Dim cols As New List(Of Color)
  Dim bytes As Integer = Math.Abs(bmpData.Stride) * bmp.Height
  Dim rgbValues(bytes - 1) As Byte
  System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
  
  ' Retrieve RGB values
  For i = modByte To rgbValues.Length Step 3
       cols.Add(Color.FromArgb(rgbValues(i + 2), rgbValues(i + 1), rgbValues(i)))
  Next
  
  bmp.UnlockBits(bmpData)
  bmp.Dispose()
  Dim colsCnt As List(Of RgbPixels) = cols.GroupBy(Function(g) New With {Key .R = g.R, Key .G = g.G, Key .B = g.B}).Select(Function(s) New RgbPixels With {.Colour = Color.FromArgb(s.Key.R, s.Key.G, s.Key.B), .Amount = s.Count()}).ToList()
  </code></pre>
  
  <p>After grouping the resulting colours, the values are something like:</p>
  
  <pre><code>R    G    B
  255  255  255
  255  255  0
  255  0    0
  0    0    255
  0    255  255
  </code></pre>
  
  <p>Or some variation of that, when they should just be:</p>
  
  <pre><code>R    G    B
  255  255  255
  0    0    0
  </code></pre>
  
  <p>Please point me in the right direction, BTW my source bmp is in PixelFormat.Format24bppRgb too, so I don't believe that is the problem. Also if you can only answer in C# that is not a problem.</p>