我正在尝试使用 LockBits 从一组图像中获取所有像素,并通过for
. 但我得到不正确的像素。我在一秒钟内更兴奋。
代码:
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));
}
}
现在我创建了一个 2x2 像素的纯蓝色图像。我的输出应该是
255 0 0 255 255 0 0 255 255 0 0 255 255 0 0 255 (ARGB)
但我得到类似的东西
颜色 [A=0, R=0, G=0, B=255] 颜色 [A=0, R=0, G=0, B=255] 颜色 [A=0, R=0, G=0, B=0] 颜色 [A=0, R=0, G=0, B=0]
我哪里错了?抱歉,如果我无法准确解释出了什么问题。基本上像素输出不正确,与输入bmp不匹配。