Search code examples
vb.netarraysrgblockbits

Where are the RGB values stored in this array?


I've been using the following sub in my control that I'm creating to let me modify the pixels in a bitmap faster:

    Protected Sub LockForMemory()
        idata = ime.LockBits(New Rectangle(0, 0, ime.Width, ime.Height), ImageLockMode.WriteOnly, ime.PixelFormat)
        ipoint = idata.Scan0

        ibytes = Math.Abs(idata.Stride) * ime.Height
        ReDim irgbvalues(ibytes - 1)
        System.Runtime.InteropServices.Marshal.Copy(ipoint, irgbvalues, 0, ibytes)
    End Sub

All of that works, later when I go to retrieve the actual image after manipulation, it works fine as well. The problem is setting those actual pixels.

What is this array of? I know that it's filled with Integers but what does each indice represent? At first I thought it was setup like this:

Array-> [R of Pixel 0,0][G of Pixel 0,0][B of Pixel 0,0][R of Pixel 2,0][G of Pixel 2,0][B of Pixel 2,0]

This doesn't seem to work right, however.


Solution

  • It depends on the value of ime.PixelFormat. Each pixel may be represented as RGB, ARGB, palette look-up index, etc.

    http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx

    Also, you need to be careful of byte-order. The bytes would likely be in little-endian byte-order, but it depends on your target platform.

    For Format32bppArgb, this may shed some light on the format:

    PixelFormat.Format32bppArgb seems to have wrong byte order