I am trying to get all the pixels from a set image using LockBits and iterating through every pixel via for
. But i am getting incorrect pixels. I exhilarate more in a second.
Code:
Bitmap bmp = new Bitmap(ImagePath);
pictureBox1.Image = bmp;
Rectangle bmpRec = new Rectangle(0, 0,
bmp.Width, bmp.Height); // Creates Rectangle for holding picture
BitmapData bmpData = bmp.LockBits(bmpRec,
ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb); // Gets the Bitmap data
IntPtr Pointer = bmpData.Scan0; // Set pointer
int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height; // Gets array size
byte[] rgbValues = new byte[DataBytes]; // Creates array
Marshal.Copy(Pointer, rgbValues, 0, DataBytes); // Copies of out memory
StringBuilder Pix = new StringBuilder(" ");
// pictureBox1.Image = bmp;
StringBuilder EachPixel = new StringBuilder("");
for (int i = 0; i < bmpData.Width; i++)
{
for (int j = 0; j < bmpData.Height; j++)
{
var pixel = rgbValues[i + j * Math.Abs(bmpData.Stride)];
Pix.Append(" ");
Pix.Append(Color.FromArgb(pixel));
}
}
Now I have created a 2x2 pixel image of pure blue. My output should be
255 0 0 255 255 0 0 255 255 0 0 255 255 0 0 255 (A R G B)
but i get something like
Color [A=0, R=0, G=0, B=255] Color [A=0, R=0, G=0, B=255] Color [A=0, R=0, G=0, B=0] Color [A=0, R=0, G=0, B=0]
Where am I going wrong? Sorry if I can't explain exactly whats wrong. Basically the pixel output is incorrect and doesn't match up with the input bmp.