C# 图像搜索 DLL

C# ImageSearch DLL

所以我最近做了一个程序,它在屏幕上找到特定的图像和 returns 它的位置,我实际上在 Whosebug 上找到了这部分代码,它使用 ImageSearch.dll 来自AutoIT3.

效果很好,但是,缺少一件事,我不知道该怎么做。我的意思是宽容。这是其作用的原始定义:

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

基本上可以找到图像,即使有一些差异。

所以这是我得到的代码:

    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;
    }

而且我想以某种方式使公差与原始版本一样有效。那可能吗?感谢您的帮助!

我实际上想做同样的事情,所以我想我会 post 我是怎么做的。我向 UseImageSearch() 添加了第二个参数 string tolerance,并附加了 tolerance 字符串,前缀为 * 并且 post 固定为 space 到 imgPath 字符串,我将新字符串传递给 DLL,它返回具有所需结果的字符串 []。

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

我参考了这些人

[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;
    }

然后我使用图像路径和所需的容差级别 0-255 调用了 UseImageSearch

 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]);
        }

它的表现符合预期。