/// <summary> /// 传入验证码图片返回验证码字符 /// </summary> /// <param name="imgSrc"></param> /// <returns>验证码字符窜</returns> public string GetCodeString(Image imgSrc) { if (m_ci == null) { throw new Exception("Please load CodeInfo"); } if (m_ci.GetChars().Count == 0) { throw new Exception("Can not found font libary"); } string strCode = string.Empty; int nBlackCount = 0, nWhiteCount = 0; Image img_dark = null; List <Rectangle> lstChar = null; if (m_ci.IsAutoSelectRect) { m_ci.CodeCount = m_ci.CodeRectangles.Count; } for (int i = 0, len = m_ci.CodeCount == 0 ? 1 : m_ci.BinaryValues.Length; i < len; i++) { img_dark = this.GetBinaryImage(imgSrc, m_ci.BinaryValues[i], out nBlackCount, out nWhiteCount, m_ci.Express); if (nBlackCount > nWhiteCount) { img_dark = this.ReverseColors(img_dark); } if (m_ci.RectangleCut.Size != img_dark.Size) { Bitmap bmp = new Bitmap(m_ci.RectangleCut.Width, m_ci.RectangleCut.Height); using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(img_dark, new Rectangle(Point.Empty, bmp.Size), m_ci.RectangleCut, GraphicsUnit.Pixel); img_dark = bmp; } } lstChar = this.GetCharRect((Bitmap)img_dark, m_ci.PixelMin, m_ci.PixelMax); if (lstChar.Count == m_ci.CodeCount) { break; } } if (!m_ci.IsAutoSelectRect) { lstChar = m_ci.CodeRectangles; } foreach (var v in lstChar) { strCode += this.GetBestSameChar((Bitmap)img_dark, v); } return(strCode.Replace("-", "")); }
/// <summary> /// 从样本中获取最相似的图像并返回字符 /// </summary> /// <param name="imgDarkCodeImage">验证码图像</param> /// <param name="rect">字符所在的区域</param> /// <returns>最相识的字符</returns> private char GetBestSameChar(Image imgDarkCodeImage, Rectangle rect) { char chCode = '*'; using (Bitmap bmpChar = new Bitmap(rect.Width, rect.Height)) { using (Graphics g = Graphics.FromImage(bmpChar)) { g.DrawImage(imgDarkCodeImage, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel); int nSameCount = 0; foreach (var v in m_ci.GetChars()) { int nTemp = this.GetBestSameCount(bmpChar, v); if (nTemp > nSameCount) { nSameCount = nTemp; chCode = v; } } } } return(chCode); }