【问题标题】:Pixel Output Incorrect像素输出不正确
【发布时间】:2014-05-08 00:08:59
【问题描述】:

我正在尝试使用 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 (A R G B)

但我得到了类似的东西

颜色 [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不匹配。

【问题讨论】:

  • 我可以看到的一个问题是,您将 rgbValues 作为字节数组读取,而 var pixel 是一个字节,但 Color.FromArgb 将 int 作为参数。
  • 不是直接的。并用不同的语言写成。 @RichardSchneider
  • @Rynoh97:只是语言不同,核心和库是一样的。还要删除与计时器无关的代码。

标签: c# graphics pixels imaging lockbits


【解决方案1】:

我不确定您究竟想在这里做什么...我认为您误解了 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);
        }
    }
}

【讨论】:

    【解决方案2】:

    通过更改输出内容和方式来解决问题。 我现在使用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];
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      相关资源
      最近更新 更多