I'm trying to copy the contents of an OpenGL (using OpenTK) viewport into a C# Bitmap. I'm using this code:
BitmapData data = bmp.LockBits(Rectangle.FromLTRB(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
GL.ReadPixels(0, 0, bmp.Width, bmp.Height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
I've seen code similar to this all over the internet and for the most part, it works fine. But in obscure circumstances, when the width of the bitmap is one a few particular values, it doesn't. The data variable comes back with a stride that does not match the Width and the result is an image heavily skewed to the left.
Has anyone else noticed this behavior? Is it something I'm doing, or is it there some workaround that I need to know about?
edit: Per Fiddler's advice, I've amended my code to:
BitmapData data = bmp.LockBits(dest, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
GL.PushClientAttrib(ClientAttribMask.ClientPixelStoreBit);
GL.PixelStore(PixelStoreParameter.PackAlignment, 4);
GL.ReadPixels(0, 0, bmp.Width, bmp.Height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);
GL.PopClientAttrib();
bmp.UnlockBits(data);
Doesn't seem to make a difference. Have tried values of 1,2,4, and 8 for PixelStore, and also have tried UnpackAlignment with same values. Could there be another setting at play here?