Question

I currently have the following code which will take a screenshot and check each pixel one at a time if it matches the color I have specified. If it matches then it will move the mouse to the specific pixel location.

I am currently looking for a better and faster way of doing this if anybody is able to help out.

If you don't want to read the entire code I will explain the process right here: Basically the program will take a screenshot, and analyze it 1 pixel at a time comparing it to the desired color. It will start in the top left pixel and horizontally moving down one row at a time and if it was unable to find the pixel it will restart. This code also will only work for a 1080p screen which is fine for me.

Now the code WORKS I am just looking for a more efficient way than scanning 2 Million + pixels.

Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
              Screen.PrimaryScreen.Bounds.Height);
        Graphics graphics = Graphics.FromImage(bitmap as Image);
        graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

        bool found = false;

        bool one = true;
        bool two = false;

        int x = 0;
        int y = 0;

        Bitmap myBitmap = bitmap;
        while (found != true)
        {
            Color pixelColor = myBitmap.GetPixel(x, y);
            if (pixelColor == Color.FromArgb(0, 0, 0))
            {
                Cursor.Position = new Point(x, y);
                found = true;
            }
            if (one == true)
            {
                x = x + 1;
                if (x >= 1920)
                {
                    one = false;
                    two = true;
                    x = 0;
                }
            }
            else if (two == true)
            {
                y = y + 1;
                if (y >= 1080)
                {
                    y = 0;
                }
                one = true;
                two = false;
            }
        }
Was it helpful?

Solution

You cannot really practically avoid the linear search, but you can make it much faster by using Bitmap.LockBits().

Bitmap.LockBits() will let you block copy areas of the bitmap into a local array that you can much more quickly search for the target colour.

Unfortunately this is a lot more fiddly to use than GetPixel() but it can be very much faster.

Also see here for an example: http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top