public static Bitmap CleanUnecessaryPixel(this Bitmap image, CaptchaInfo info) { var colorList = info.Colors.Keys.ToList().Where(x => x != info.BackgroundColor).ToList(); int connections = 2; for (int y = 0; y < image.Height; y++) { for (int x = 0; x < image.Width; x++) { Color pixel = image.GetPixel(x, y); // Skip background pixel if (pixel.Name == info.BackgroundColor) { continue; } if (colorList.Contains(pixel.Name)) { bool connected = IsPixelWithinRadius(x, y, image, info, connections); if (!connected) { image.SetPixel(x, y, ColorTranslator.FromHtml("#" + info.BackgroundColor)); } } } } return(image); }
public static Bitmap GetCaptchaInfo(this Bitmap image, ref CaptchaInfo info) { for (int i = 0; i < image.Width; i++) { for (int j = 0; j < image.Height; j++) { Color pixel = image.GetPixel(i, j); if (!info.Colors.ContainsKey(pixel.Name)) { info.Colors[pixel.Name] = 1; } else { info.Colors[pixel.Name] = info.Colors[pixel.Name] + 1; } } } var list = info.Colors.Values.ToList(); list.Sort(); list.Reverse(); info.BackgroundColor = ""; info.CaptchaColor = ""; foreach (var item in info.Colors) { if (item.Value == list[0] && string.IsNullOrEmpty(info.BackgroundColor)) { info.BackgroundColor = item.Key; continue; } if (item.Value == list[1] && string.IsNullOrEmpty(info.CaptchaColor)) { info.CaptchaColor = item.Key; continue; } info.IrrelevantColor.Add(item.Key); } return(image); }
private static bool IsPixelWithinRadius(int x, int y, Bitmap img, CaptchaInfo info, int connections = 3) { try { // Check left, right, bottomLeft, bottom, bottomRight, topLeft, top, topRight Color color = img.GetPixel(x, y); int count = 0; //left if (x - 1 >= 0) { color = img.GetPixel(x - 1, y); if (info.CaptchaColor == color.Name) { count++; } } //right if (x + 1 < img.Width) { color = img.GetPixel(x + 1, y); if (info.CaptchaColor == color.Name) { count++; } } //top if (y - 1 >= 0) { color = img.GetPixel(x, y - 1); if (info.CaptchaColor == color.Name) { count++; } } //top left if (y - 1 >= 0 && x - 1 >= 0) { color = img.GetPixel(x - 1, y - 1); if (info.CaptchaColor == color.Name) { count++; } } //top right if (y - 1 >= 0 && x + 1 >= 0) { color = img.GetPixel(x + 1, y - 1); if (info.CaptchaColor == color.Name) { count++; } } //bottomLeft if (y + 1 < img.Height && x - 1 >= 0) { color = img.GetPixel(x - 1, y + 1); if (info.CaptchaColor == color.Name) { count++; } } //bottomRight if (y + 1 < img.Height && x + 1 < img.Width) { color = img.GetPixel(x + 1, y + 1); if (info.CaptchaColor == color.Name) { count++; } } //bottom if (y + 1 < img.Height) { color = img.GetPixel(x, y + 1); if (info.CaptchaColor == color.Name) { count++; } } return(count >= connections); } catch { } return(true); }