- 引言
最近,由于工作上的某些原因,又要写类似于外挂的程序,又要用到一个屏幕找图功能,很多程序(eg:按键精灵)都提供了类似的功能,其实在这之前,我也查找过很多类似的C#方法,因为之前有一个试过没有用得起,所以最后就放弃了,知道现在都是使用的自己写的一个,相对来说,除了效率比较慢,没有太大的问题。不过就是由于效率不高,后面又想了其他的一些解决办法。
- 基础+贴代码。
因为是一些图片处理和操作,所以必不可少的会用到C# GDI+的一些基本知识,对于这个网上应该也有很多,大家可以拿来学习和参考。
再者,其实细细想一下,其实应该很简单,为什么呢,因为就是一个一个像素的比较,比较颜色差异,没有差异就通过,有差异,就继续查找,知道找到必须要,且完全匹配就OK。
于是乎有了下面的代码。1.0
// 基础代码和调用代码 (注释基本,略,后面又没有添加,多多包涵)


1 public class ImageManager 2 { 3 public static Point Compare(Bitmap bigImage, Bitmap smallImage) 4 { 5 for (int i = 0; i < bigImage.Width; i++) 6 { 7 for (int j = 0; j < bigImage.Height; j++) 8 { 9 Color c1 = bigImage.GetPixel(i, j); 10 Color c2 = smallImage.GetPixel(0, 0); 11 12 // 颜色相等,且没有超出边界 13 if (Compare(c1, c2) && bigImage.Width >= (i + smallImage.Width) && bigImage.Height >= (j + smallImage.Height)) 14 { 15 bool iscontinue = false; 16 for (int x = 0; x < smallImage.Width; x++) 17 { 18 for (int y = 0; y < smallImage.Height; y++) 19 { 20 Color c3 = smallImage.GetPixel(x, y); 21 Color c4 = bigImage.GetPixel(i + x, j + y); 22 if (!Compare(c3, c4)) 23 { 24 iscontinue = true; 25 break; 26 } 27 } 28 29 if (iscontinue) 30 { 31 break; 32 } 33 } 34 35 if (!iscontinue) 36 { 37 return new Point(i, j); 38 } 39 } 40 } 41 } 42 43 return new Point(-1, -1); 44 } 45 46 private static bool Compare(Color c1, Color c2) 47 { 48 if (c1.A == c2.A && c1.R == c2.R && c1.B == c2.B && c1.G == c2.G) 49 { 50 return true; 51 } 52 53 return false; 54 } 55 }