C# 像素输出不正确

C# 像素输出不正确,c#,graphics,pixels,imaging,lockbits,C#,Graphics,Pixels,Imaging,Lockbits,我试图使用锁位从一组图像中获取所有像素,并通过for对每个像素进行迭代。但我得到的像素不正确。我在一秒钟内更加兴奋 代码: Bitmap bmp=新位图(ImagePath); pictureBox1.Image=bmp; 矩形bmpRec=新矩形(0,0, bmp.宽度,bmp.高度);//创建用于保存图片的矩形 BitmapData bmpData=bmp.LockBits(bmpRec, ImageLockMode.ReadWrite, PixelFormat.Format32bppArg

我试图使用锁位从一组图像中获取所有像素,并通过
for
对每个像素进行迭代。但我得到的像素不正确。我在一秒钟内更加兴奋

代码:

Bitmap bmp=新位图(ImagePath);
pictureBox1.Image=bmp;
矩形bmpRec=新矩形(0,0,
bmp.宽度,bmp.高度);//创建用于保存图片的矩形
BitmapData bmpData=bmp.LockBits(bmpRec,
ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb);//获取位图数据
IntPtr Pointer=bmpData.Scan0;//设置指针
int-DataBytes=Math.Abs(bmpData.Stride)*bmp.Height;//获取数组大小
字节[]rgbValues=新字节[数据字节];//创建数组
Marshal.Copy(指针、RGB值、0、数据字节);//内存不足的副本
StringBuilder Pix=新的StringBuilder(“”);
//pictureBox1.Image=bmp;
StringBuilder EachPixel=新StringBuilder(“”);
对于(int i=0;i
现在我已经创建了一个2x2像素的纯蓝色图像。我的输出应该是

255 0 0 255 0 0 255 0 0 255 0 0 255 0 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不匹配。

我不确定您在这里到底想做什么。。。我想你误解了Scan0和Stride的工作原理。Scan0是指向内存中图像开头的指针。Stride是内存中每行的长度(以字节为单位)。您已使用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);
        }
    }
}
Bitmap bmp=新位图(ImagePath);
BitmapData bmpData=bmp.LockBits(新矩形(0,0,bmp.Width,bmp.Height),ImageLockMode.ReadWrite,PixelFormat.Format32bppArgb);
StringBuilder sb=新的StringBuilder();
不安全的
{
对于(int y=0;y
通过更改输出内容和方式修复了该问题。 我现在使用
Color ARGB=Color。从ARGB(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];

我看到的一个问题是,您将RGB值作为字节数组读取,
var pixel
是一个字节,而Color.FromArgb将int作为其参数。可能的重复项不是直接读取的。并且使用不同的语言编写@RichardSchneider@Rynoh97:仅语言不同,核心和库相同。同时删除t他编写了与问题无关的代码,比如计时器。
byte B = row[(x * 4)];
byte G = row[(x * 4) + 1];
byte R = row[(x * 4) + 2];
byte A = row[(x * 4) + 3];