LockBits get pixel (X, Y)

545 Views Asked by At

Currently I have this, I am searching for the RGB value (208, 94, 94) and if there is a match, it will tell my DX device to draw on the screen and aswell log it in the console.

Well, I am not exactly sure how to get the exact X,Y coordinates of the pixel. The Y is fine and not the problem, but the X is always off and a high value. How should I get the X, Y? Is there a formula or is my code wrong? Is there a way to use GetPixel inside LockBits with it being fast?

For example it prints:

x: 3772 y: 187 when the actual value is: 944, 187

x: 3888 y: 212 when the actual value is: 973, 212

x: 3788 y: 224 when the actual value is: 948, 224

unsafe
{
    using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("FileName.png"))
    {

        BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
        int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
        int heightInPixels = bitmapData.Height;
        int widthInBytes = bitmapData.Width * bytesPerPixel;
        byte* ptrFirstPixel = (byte*)bitmapData.Scan0;

        for (int y = 0; y < heightInPixels; y++)
        {
            byte* currentLine = ptrFirstPixel + (y * bitmapData.Stride);


            for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
            {
                int Blue = currentLine[x];
                int Green = currentLine[x + 1];
                int Red = currentLine[x + 2];

                if (Red == 208 & Green == 94 & Blue == 94)
                {
                   // Device.DrawText("Unit", TextFont, new RawRectangleF(x, y, float.MaxValue, float.MaxValue), UnitTextBrush);

                    Console.WriteLine($"x: {x} y: {y}");

                    break;
                }
            }
        }

        bmp.UnlockBits(bitmapData);
    }
}
0

There are 0 best solutions below