-1

我正在尝试使用 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不匹配。

4

2 回答 2

0

通过更改输出的内容和方式来解决问题。我现在使用Color ARGB = Color.FromArgb(A, R, G, B)我现在也使用像素阵列。

byte B = row[(x * 4)];
byte G = row[(x * 4) + 1];
byte R = row[(x * 4) + 2];
byte A = row[(x * 4) + 3];
于 2014-05-13T02:09:56.623 回答
0

我不确定你到底想在这里做什么......我认为你误解了 Scan0 和 Stride 的工作原理。Scan0 是指向内存中图像开头的指针。步幅是内存中每一行的长度(以字节为单位)。您已经使用 bmp.LockBits 将图像锁定到内存中,您不必对其进行编组。

Bitmap bmp = new Bitmap(ImagePath);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
StringBuilder sb = new StringBuilder();

unsafe
{
    for (int y = 0; y < bmp.Height; y++)
    {
        byte* row = (byte*)bmpData.Scan0 + (y * bmpData.Stride);
        for (int x = 0; x < bmp.Width; x++)
        {
            byte B = row[(x * 4)];
            byte G = row[(x * 4) + 1];
            byte R = row[(x * 4) + 2];
            byte A = row[(x * 4) + 3];
            sb.Append(String.Format("{0} {1} {2} {3} ", A, R, G, B);
        }
    }
}
于 2014-05-12T15:55:24.933 回答