【发布时间】: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