I am getting bitmaps from a buffer from a net cam. When I assign these to a PictureBox the red and blue are reversed.
What can I do to the bitmap or to the PictureBox to get the red and blue in their proper places?
I am getting bitmaps from a buffer from a net cam. When I assign these to a PictureBox the red and blue are reversed.
What can I do to the bitmap or to the PictureBox to get the red and blue in their proper places?
The following code does the needed conversion:
public static void RGBtoBGR(Bitmap bmp)
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite, bmp.PixelFormat);
int length = Math.Abs(data.Stride) * bmp.Height;
unsafe
{
byte* rgbValues = (byte*)data.Scan0.ToPointer();
for (int i = 0; i < length; i += 3)
{
byte dummy = rgbValues[i];
rgbValues[i] = rgbValues[i + 2];
rgbValues[i + 2] = dummy;
}
}
bmp.UnlockBits(data);
}
LockBits
locks the bitmap in memory so that you can access and change the contents directly. If you don't want to have an unsafe context you can create a byte array and use Marshal.Copy
to copy the data into it and back to the bitmap after manipulating. Using LockBits
is the fastest option to manipulate bitmap data (much faster than GetPixel
or SetPixel
).
The loop iterator (i += 3
) depends on the PixelFormat
of the bitmap. Here I am assuming it is PixelFormat.Format24bppRgb
. For Format32bppArgb
it would be i += 4
.