I'm using a similar method like this answer to create a bitmap from a byte array.
private static void MySaveBMP(byte[] buffer, int width, int height)
{
Bitmap b = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Rectangle BoundsRect = new Rectangle(0, 0, width, height);
BitmapData bmpData = b.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
b.PixelFormat);
IntPtr ptr = bmpData.Scan0;
// fill in rgbValues
Marshal.Copy(buffer, 0, ptr, buffer.Length);
b.UnlockBits(bmpData);
b.Save(@"D:\myPic.bmp", ImageFormat.Bmp);
}
And I generate a byte array, fill in some values like this:
int width = 20;
int height = 30;
int bytesPerPixel = 3;
int bytesPerRow = width * bytesPerPixel;
int totalLength = bytesPerRow * height;
byte[] managedArray = new byte[totalLength];
// fill background with white
for (int i = 0; i < totalLength; i++)
managedArray[i] = 255;
// draw on each row
for (int i = 0; i < height; i++)
{
// first pixel is green
managedArray[0 + i * bytesPerRow] = 0;
managedArray[1 + i * bytesPerRow] = 255;
managedArray[2 + i * bytesPerRow] = 0;
// last pixel is red
managedArray[bytesPerRow - 3 + i * bytesPerRow] = 0;
managedArray[bytesPerRow - 2 + i * bytesPerRow] = 0;
managedArray[bytesPerRow - 1 + i * bytesPerRow] = 255;
}
MySaveBMP(managedArray, width, height);
The resulting 20x30 bmp image looks like this:
However, if I change the image height (for example, to 21), the resulting image seems corrupted. Each row looks like it shift to left a bit:
What am I doing wrong while making the bitmap image?