C# ImageSearch DLL

2019-09-18 18:05发布

So I have recently made a program which finds specific image on the screen and returns the location of it, I actually found this part of the code on stackoverflow, which is using ImageSearch.dll from AutoIT3.

It works pretty well, however, there's one thing missing and I have no idea how to do it. I mean tolerance. This is the original definition of what it does:

";                $tolerance - 0 for no tolerance (0-255). Needed when colors of
;                            image differ from desktop. e.g GIF"

Basically allows to find the image even if there are a few differences.

So this is the code I've got:

    DllImport("ImageSearch.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

        public static string[] UseImageSearch(string imgPath)
    {

        IntPtr result = ImageSearch(0, 0, Screen.PrimaryScreen.WorkingArea.Right, Screen.PrimaryScreen.WorkingArea.Bottom, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }

And I'd like to somehow make the tolerance work as it is in the original. Is that possible? Thanks for any help!

1条回答
Melony?
2楼-- · 2019-09-18 18:56

I was actually wanting to do the same thing so I figured I would post how I did it. I added a second parameter, string tolerance, to UseImageSearch() and appended the tolerance string, prefixed with an * and postfixed with a space to the imgPath string, I passed the new string to the DLL and it returned a string[] with the desired results.

using System;
using System.Runtime.InteropServices;
using System.Windows;

I referenced these guys

[DllImport(@"C:\ImageSearchDLL.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

    public static string[] UseImageSearch(string imgPath, string tolerance)
    {
        imgPath = "*" + tolerance + " " + imgPath;

        IntPtr result = ImageSearch(0, 0, 1920, 1080, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }

Then I called UseImageSearch using the image path and the desired tolerance level 0-255

 string image = (@"C:\Capture.PNG");

        string[] results = UseImageSearch(image, "30");
        if (results == null)
        {
            MessageBox.Show("null value bro, sad day");
        }
        else
        {
            MessageBox.Show(results[1] + ", " + results[2]);
        }

It performed as desired.

enter image description here

查看更多
登录 后发表回答