C#检查图像是否出现在屏幕上

时间:2016-07-23 03:49:42

标签: c# image

我有一个应该出现在屏幕上的裁剪版图片。

Image 6Island = Image.FromFile("C:\\Users\\6Island.png");

现在,下一个目标是拍摄屏幕图像。

Bitmap CaptureScreen()
    {
        var image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        var gfx = Graphics.FromImage(image);
        gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        return image;
    }

Image 6Island = Image.FromFile("C:\\Users\\6Island.png");
Image currentView = CaptureScreen();

然后我想看看能否在新图像中找到图像6Island。颜色可能会有所不同。反正有吗?

1 个答案:

答案 0 :(得分:2)

这只是样本快速而肮脏且非常慢,但它可以正常工作。此代码会对您的大位图进行“裁剪”,并将其与您的小位图进行比较。如果相等则百分比必须为100,如果不相等则低于该百分比。我会说,如果超过98%,那么你就找到了它。

private static void CompareBigAndSmallBitmaps(string fileName1, string fileName2)
{
  var bmpBig = (Bitmap) Image.FromFile(fileName1);
  var bmpSmall = (Bitmap) Image.FromFile(fileName2);
  for (var offX = 0; offX < bmpBig.Width - bmpSmall.Width; offX++)
  {
    for (var offY = 0; offY < bmpBig.Height - bmpSmall.Height; offY++)
    {
      var percentage = CompareSmallBitmaps(bmpBig, bmpSmall, offX, offY);
      if (percentage > 98.0)  // define percentage of equality
      {
        // Aha... found something here....and exit here if you want
      }
    }
  }
}

private static double CompareSmallBitmaps(Bitmap bmpBig, Bitmap bmpSmall, int offX, int offY)
{
  var equals = 0;
  for (var x = 0; x < bmpSmall.Width; x++)
  {
    for (var y = 0; y < bmpSmall.Height; y++)
    {
      var color1 = bmpBig.GetPixel(x + offX, y + offY).ToArgb();
      var color2 = bmpSmall.GetPixel(x, y).ToArgb();
      if (color1 == color2)
      {
        equals++;
      }
    }
  }
  return (Convert.ToDouble(equals)/Convert.ToDouble(bmpSmall.Width*bmpSmall.Height))*100.0;
}