我目前有一个代码可以在此程序截取的屏幕截图中搜索位图,但是,位图在屏幕截图中存在三次,我希望它在第二次找到时点击。
有没有办法做到这一点?非常感谢...
代码:
private Bitmap Screenshot()
{
Bitmap bmpScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bmpScreenShot);
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
return bmpScreenShot;
}
private bool FindBitmap(Bitmap BmpNeedle, Bitmap BmpHaystack, out Point location)
{
for (int outerX = 0; outerX < BmpHaystack.Width - BmpNeedle.Width; outerX++)
{
for (int outerY = 0; outerY < BmpHaystack.Height - BmpNeedle.Height; outerY++)
{
for (int innerX = 0; innerX < BmpNeedle.Width; innerX++)
{
for (int innerY = 0; innerY < BmpNeedle.Height; innerY++)
{
Color cNeedle = BmpNeedle.GetPixel(innerX, innerY);
Color cHaystack = BmpHaystack.GetPixel(innerX + outerX, innerY + outerY);
if (cNeedle.R != cHaystack.R || cNeedle.G != cHaystack.G || cNeedle.B != cHaystack.B)
{
continue;
}
}
}
location = new Point(outerX, outerY);
return true;
}
}
location = Point.Empty;
return false;
}
public void findImage()
{
Bitmap bmpScreenshot = Screenshot();
Point location;
bool success = FindBitmap(Properties.Resources.xxx, bmpScreenshot, out location);
}
不知道这是否真的有帮助,我想要它做的就是点击它找到的第二个位图。
一位朋友确实建议将我的屏幕截图拆分为网格,然后这样做,为什么,要做网格还是可以找到第二个位图?
更新:说我的屏幕上有5张完全相同的图片。我希望我的程序单击它找到的第三个位图。
答案 0 :(得分:1)
最简单的方法是引入一个计数器,显示图片被发现的次数。不知怎的,这样:
private bool FindBitmap(Bitmap BmpNeedle, Bitmap BmpHaystack, out Point location)
{
int countTimesFound = 0;
for (int outerX = 0; outerX < BmpHaystack.Width - BmpNeedle.Width; outerX++)
{
for (int outerY = 0; outerY < BmpHaystack.Height - BmpNeedle.Height; outerY++)
{
for (int innerX = 0; innerX < BmpNeedle.Width; innerX++)
{
for (int innerY = 0; innerY < BmpNeedle.Height; innerY++)
{
Color cNeedle = BmpNeedle.GetPixel(innerX, innerY);
Color cHaystack = BmpHaystack.GetPixel(innerX + outerX, innerY + outerY);
if (cNeedle.R != cHaystack.R || cNeedle.G != cHaystack.G || cNeedle.B != cHaystack.B)
{
continue;
}
}
}
countTimesFound++;
if (countTimesFound == 2)
{
location = new Point(outerX, outerY);
return true;
}
}
}
location = Point.Empty;
return false;
}
虽然你应该真正研究图像检测技术。有些库允许这样做更容易。