在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → c# 验证码解析识别 示例代码

c# 验证码解析识别 示例代码

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:1.97M
  • 下载次数:74
  • 浏览次数:574
  • 发布时间:2017-07-08
  • 实例类别:C#语言基础
  • 发 布 人:wukui1992101
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 验证码 验证 解析

实例介绍

【实例简介】因调用的是 蜂巢系统的验证码,蜂巢系统已下架,所以 实例运行会提示错误,不过代码可参考

【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.Text;

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace BaiduCodeReader
{
    public static class BaiduCodeHelper
    {
        static BaiduCodeHelper() {
            m_codeImageModel = (CodeImageModel)ByteToObject(Properties.Resources.CodeModelData);
        }

        public static object ByteToObject(byte[] bytes) {
            try {
                System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
                System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Object reobj = bf.Deserialize(stream);
                stream.Close();
                return reobj;
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 模板图片数据【从 GetModelImgData 获得】
        /// </summary>
        public static BitmapData m_bmpData;
        /// <summary>
        /// 模板图片颜色信息【从 GetModelImgData 获得】
        /// </summary>
        public static byte[] m_byColorInfo;
        /// <summary>
        /// 样本数据
        /// </summary>
        public static CodeImageModel m_codeImageModel;
        /// <summary>
        /// 从图片获取验证码
        /// </summary>
        /// <param name="bmpCode">验证码图片</param>
        /// <returns>验证码</returns>
        public static string GetCodeString(Bitmap bmpCode) {
            lock (m_codeImageModel) {
                Bitmap bmpDarkImage = GetDarkImage(bmpCode);
                List<Rectangle> lstRect = GetCharRect(bmpDarkImage);
                //GetCharRect里面忘了对原图做备份 所以重新用原图获取一次二值图像
                bmpDarkImage.Dispose();
                bmpDarkImage = GetDarkImage(bmpCode);
                string strCode = string.Empty;
                for (int i = 0; i < lstRect.Count; i  ) {
                    strCode  = GetBestSameChar(bmpDarkImage, lstRect[i]);
                }
                bmpDarkImage.Dispose();
                return strCode;
            }
        }
        /// <summary>
        /// 获取验证码图片的二值图
        /// </summary>
        /// <param name="bmpSrc">验证码原图</param>
        /// <returns>二值图像</returns>
        public static Bitmap GetDarkImage(Bitmap bmpSrc) {
            Bitmap b = new Bitmap(bmpSrc);
            Bitmap bmp = b.Clone(new Rectangle(0, 0, bmpSrc.Width, bmpSrc.Height), PixelFormat.Format24bppRgb);
            b.Dispose();
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
            byte[] byColorInfo = new byte[bmp.Height * bmpData.Stride];
            Marshal.Copy(bmpData.Scan0, byColorInfo, 0, byColorInfo.Length);
            for (int x = 0, xLen = bmp.Width; x < xLen; x  ) {
                for (int y = 0, yLen = bmp.Height; y < yLen; y  ) {
                    byte byV = GetAvg(
                        byColorInfo[y * bmpData.Stride   x * 3],
                        byColorInfo[y * bmpData.Stride   x * 3   1],
                        byColorInfo[y * bmpData.Stride   x * 3   2]);
                    if ((byColorInfo[y * bmpData.Stride   x * 3] <= 60
                        && byColorInfo[y * bmpData.Stride   x * 3   1] <= 60
                        && byColorInfo[y * bmpData.Stride   x * 3   2] <= 60) || byV <= 30)
                        byV = 255;
                    else byV = (byte)(byV >= 127 ? 255 : 0);
                    byColorInfo[y * bmpData.Stride   x * 3] =
                        byColorInfo[y * bmpData.Stride   x * 3   1] =
                        byColorInfo[y * bmpData.Stride   x * 3   2] = byV;
                }
            }
            Marshal.Copy(byColorInfo, 0, bmpData.Scan0, byColorInfo.Length);
            bmp.UnlockBits(bmpData);
            return bmp;
        }
        /// <summary>
        /// 获取验证码字符区域
        /// </summary>
        /// <param name="bmpDarkImage">二值后的验证码图像</param>
        /// <returns>字符区域</returns>
        public static List<Rectangle> GetCharRect(Bitmap bmpDarkImage) {
            List<Rectangle> lstRect = new List<Rectangle>();
            for (int y = 0, leny = bmpDarkImage.Height; y < leny; y  ) {
                for (int x = 0, lenx = bmpDarkImage.Width; x < lenx; x  ) {
                    if (bmpDarkImage.GetPixel(x, y).ToArgb() == Color.Black.ToArgb()) {
                        Rectangle rectTemp = GetRegionFromPoint(bmpDarkImage, new Point(x, y), Color.Black, Color.Blue);
                        if (rectTemp != Rectangle.Empty) lstRect.Add(rectTemp);
                    }
                }
            }
            //将区域按照left属性排序
            for (int i = 0; i < lstRect.Count; i  ) {
                for (int j = 1; j < lstRect.Count - i; j  ) {
                    if (lstRect[j - 1].Left > lstRect[j].Left) {
                        Rectangle rectTemp = lstRect[j];
                        lstRect[j] = lstRect[j - 1];
                        lstRect[j - 1] = rectTemp;
                    }
                }
            }
            return lstRect;
        }
        /// <summary>
        /// 更具一个点获取图像上与改点颜色相同的连同区域
        /// </summary>
        /// <param name="bmpDarkImage">二值后的验证码</param>
        /// <param name="ptStart">定点坐标</param>
        /// <param name="clrSrc">定点颜色</param>
        /// <param name="clrSet">提取点后重置点颜色</param>
        /// <returns></returns>
        public static Rectangle GetRegionFromPoint(Bitmap bmpDarkImage, Point ptStart, Color clrSrc, Color clrSet) {
            int nCount = 0;
            Rectangle rect = new Rectangle(ptStart.X, ptStart.Y, 0, 0);
            List<Point> ptRegList = new List<Point>();
            ptRegList.Add(ptStart);
            bmpDarkImage.SetPixel(ptStart.X, ptStart.Y, clrSet);
            while (ptRegList.Count != 0) {
                Point ptTemp = GetNextPoint(bmpDarkImage, ptRegList[ptRegList.Count - 1], clrSrc);
                if (ptTemp != Point.Empty) {
                    ptRegList.Add(ptTemp);
                    bmpDarkImage.SetPixel(ptTemp.X, ptTemp.Y, clrSet);
                    nCount  ;
                    if (ptTemp.X < rect.Left) { rect.Width = rect.Right - ptTemp.X; rect.X = ptTemp.X; }
                    if (ptTemp.Y < rect.Top) { rect.Height = rect.Bottom - ptTemp.Y; rect.Y = ptTemp.Y; }
                    if (ptTemp.X > rect.Right) rect.Width = ptTemp.X - rect.Left;
                    if (ptTemp.Y > rect.Bottom) rect.Height = ptTemp.Y - rect.Top;
                } else
                    ptRegList.RemoveAt(ptRegList.Count - 1);
            }
            rect.Width  = 1; rect.Height  = 1;
            return nCount < 8 ? Rectangle.Empty : rect;
        }
        /// <summary>
        /// 获取验证码上一区域最相似的字符
        /// </summary>
        /// <param name="bmpDarkImage">而之后的验证码</param>
        /// <param name="rect">指定区域</param>
        /// <returns>该区域最相似的字符</returns>
        public static char GetBestSameChar(Bitmap bmpDarkImage, Rectangle rect) {
            char chCode = '0';
            using (Bitmap bmpChar = new Bitmap(rect.Width, rect.Height)) {
                using (Graphics g = Graphics.FromImage(bmpChar)) {
                    g.DrawImage(bmpDarkImage, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
                    //GetModelImgData(bmpChar);
                    int nSameCount = 0;
                    for (char ch = '2'; ch <= '9'; ch  ) {
                        int nTemp = GetBestSameCount(bmpChar, ch);
                        if (nTemp > nSameCount) { nSameCount = nTemp; chCode = ch; }
                    }
                    for (char ch = 'A'; ch <= 'Z'; ch  ) {
                        int nTemp = GetBestSameCount(bmpChar, ch);
                        if (nTemp > nSameCount) { nSameCount = nTemp; chCode = ch; }
                    }
                }
            }
            return chCode;
        }
        /// <summary>
        /// 获取图片与指定字符的相似度【备用 需调用 GetModelImgData 后使用】
        /// </summary>
        /// <param name="ch">指定字符</param>
        /// <returns>相似度</returns>
        public static int GetBestSameCount(char ch) {
            List<Bitmap> lstBmpModel = m_codeImageModel.GetCodeImages(ch);
            if (lstBmpModel == null) return 0;
            int nSameCount = 0;
            for (int j = 0, lenj = lstBmpModel.Count; j < lenj; j  ) {
                int nTemp = CmpImage(lstBmpModel[j]);
                if (nTemp > nSameCount) {
                    nSameCount = nTemp;
                }
            }
            return nSameCount;
        }
        /// <summary>
        /// 获取验证码上字符图片的相似度
        /// </summary>
        /// <param name="bmpDark">验证码上的字符图片</param>
        /// <param name="ch">指定字符</param>
        /// <returns>相似度</returns>
        public static int GetBestSameCount(Bitmap bmpDark, char ch) {
            List<Bitmap> lstBmpModel = m_codeImageModel.GetCodeImages(ch);
            if (lstBmpModel == null) return 0;
            int nSameCount = 0;
            for (int j = 0, lenj = lstBmpModel.Count; j < lenj; j  ) {
                int nTemp = CmpImage(bmpDark, lstBmpModel[j]);
                if (nTemp > nSameCount) {
                    nSameCount = nTemp;
                }
            }
            return nSameCount;
        }
        /// <summary>
        /// 比较两张图片的相似度
        /// </summary>
        /// <param name="bmpA">图片A</param>
        /// <param name="bmpB">图片B</param>
        /// <returns></returns>
        public static int CmpImage(Bitmap bmpA, Bitmap bmpB) {
            int nCount = 0;
            using (Bitmap bmpTemp = new Bitmap(bmpA.Width, bmpA.Height)) {
                using (Graphics g = Graphics.FromImage(bmpTemp)) {
                    g.DrawImage(bmpB, 0, 0, bmpA.Width, bmpA.Height);

                    BitmapData bmpDataA = bmpA.LockBits(new Rectangle(0, 0, bmpA.Width, bmpA.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    byte[] byColorInfoA = new byte[bmpA.Height * bmpDataA.Stride];
                    Marshal.Copy(bmpDataA.Scan0, byColorInfoA, 0, byColorInfoA.Length);

                    BitmapData bmpDataB = bmpTemp.LockBits(new Rectangle(0, 0, bmpTemp.Width, bmpTemp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    byte[] byColorInfoB = new byte[bmpTemp.Height * bmpDataB.Stride];
                    Marshal.Copy(bmpDataB.Scan0, byColorInfoB, 0, byColorInfoB.Length);

                    for (int x = 0, xLen = bmpA.Width; x < xLen; x  ) {
                        for (int y = 0, yLen = bmpA.Height; y < yLen; y  ) {
                            byte byA = (byte)(GetAvg(
                                byColorInfoA[y * bmpDataA.Stride   x * 3],
                                byColorInfoA[y * bmpDataA.Stride   x * 3   1],
                                byColorInfoA[y * bmpDataA.Stride   x * 3   2]) <= 30 ? 0 : 255);
                            byte byB = (byte)(GetAvg(
                                byColorInfoB[y * bmpDataB.Stride   x * 3],
                                byColorInfoB[y * bmpDataB.Stride   x * 3   1],
                                byColorInfoB[y * bmpDataB.Stride   x * 3   2]) <= 30 ? 0 : 255);
                            if (byA == byB) nCount  ;
                        }
                    }
                    Marshal.Copy(byColorInfoA, 0, bmpDataA.Scan0, byColorInfoA.Length);
                    bmpA.UnlockBits(bmpDataA);

                    Marshal.Copy(byColorInfoB, 0, bmpDataB.Scan0, byColorInfoB.Length);
                    bmpTemp.UnlockBits(bmpDataB);
                }
            }
            return nCount;
        }
        /// <summary>
        /// 比较图片的相似度【备用 需调用 GetModelImgData 后使用】
        /// </summary>
        /// <param name="bmpB">要比较的图片</param>
        /// <returns>相似度</returns>
        public static int CmpImage(Bitmap bmpB) {
            int nCount = 0;
            using (Bitmap bmpTemp = new Bitmap(m_bmpData.Width, m_bmpData.Height)) {
                using (Graphics g = Graphics.FromImage(bmpTemp)) {
                    g.DrawImage(bmpB, 0, 0, bmpTemp.Width, bmpTemp.Height);

                    BitmapData bmpDataB = bmpTemp.LockBits(new Rectangle(0, 0, bmpTemp.Width, bmpTemp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    byte[] byColorInfoB = new byte[bmpTemp.Height * bmpDataB.Stride];
                    Marshal.Copy(bmpDataB.Scan0, byColorInfoB, 0, byColorInfoB.Length);

                    for (int x = 0, xLen = m_bmpData.Width; x < xLen; x  ) {
                        for (int y = 0, yLen = m_bmpData.Height; y < yLen; y  ) {
                            byte byA = (byte)(GetAvg(
                                m_byColorInfo[y * m_bmpData.Stride   x * 3],
                                m_byColorInfo[y * m_bmpData.Stride   x * 3   1],
                                m_byColorInfo[y * m_bmpData.Stride   x * 3   2]) <= 30 ? 0 : 255);
                            byte byB = (byte)(GetAvg(
                                byColorInfoB[y * bmpDataB.Stride   x * 3],
                                byColorInfoB[y * bmpDataB.Stride   x * 3   1],
                                byColorInfoB[y * bmpDataB.Stride   x * 3   2]) <= 30 ? 0 : 255);
                            if (byA == byB) nCount  ;
                        }
                    }
                    Marshal.Copy(byColorInfoB, 0, bmpDataB.Scan0, byColorInfoB.Length);
                    bmpTemp.UnlockBits(bmpDataB);
                }
            }
            return nCount;
        }
        /// <summary>
        /// 指定一张图作为模板 
        /// 此方法在类的外部调用者调用
        /// 若指定了模板图片 则识别验证码时字符图像bmpA时 只需锁定一次bmpA数据
        /// 然后用这个数据与所有的样本文件对比
        /// 无须每次对比时传一次bmpA作为参数 然后重新锁定内存
        /// </summary>
        /// <param name="bmp">目标图像</param>
        public static void GetModelImgData(Bitmap bmp) {
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            m_byColorInfo = new byte[bmp.Height * bmpData.Stride];
            Marshal.Copy(bmpData.Scan0, m_byColorInfo, 0, m_byColorInfo.Length);
            m_bmpData = bmpData;
            bmp.UnlockBits(bmpData);
        }

        #region 获取连通区域

        /// <summary>
        /// 获取指定点的下一个连同点
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定的点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>连同的下一个坐标点</returns>
        public static Point GetNextPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (GetDownPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X, ptStart.Y   1);
            if (GetRightPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X   1, ptStart.Y);
            if (GetUpPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X, ptStart.Y - 1);
            if (GetLeftPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X - 1, ptStart.Y);
            if (GetLDPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X - 1, ptStart.Y   1);
            if (GetRDPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X   1, ptStart.Y   1);
            if (GetRUPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X   1, ptStart.Y - 1);
            if (GetLUPoint(bmpScr, ptStart, clr)) return new Point(ptStart.X - 1, ptStart.Y - 1);
            return Point.Empty;
        }
        /// <summary>
        /// 获取图像上指定点的下面一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetDownPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (bmpScr.Height <= ptStart.Y   1) return false;
            return bmpScr.GetPixel(ptStart.X, ptStart.Y   1).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的右边一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetRightPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (bmpScr.Width <= ptStart.X   1) return false;
            return bmpScr.GetPixel(ptStart.X   1, ptStart.Y).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的上边一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetUpPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (0 > ptStart.Y - 1) return false;
            return bmpScr.GetPixel(ptStart.X, ptStart.Y - 1).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的左边一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetLeftPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (0 > ptStart.X - 1) return false;
            return bmpScr.GetPixel(ptStart.X - 1, ptStart.Y).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的左下边一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetLDPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (0 > ptStart.X - 1 || bmpScr.Height <= ptStart.Y   1) return false;
            return bmpScr.GetPixel(ptStart.X - 1, ptStart.Y   1).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的右下一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetRDPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (bmpScr.Width <= ptStart.X   1 || bmpScr.Height <= ptStart.Y   1) return false;
            return bmpScr.GetPixel(ptStart.X   1, ptStart.Y   1).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的右上一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetRUPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (bmpScr.Width <= ptStart.X   1 || 0 > ptStart.Y - 1) return false;
            return bmpScr.GetPixel(ptStart.X   1, ptStart.Y - 1).ToArgb() == clr.ToArgb();
        }
        /// <summary>
        /// 获取图像上指定点的左上一个点是否与它连同
        /// </summary>
        /// <param name="bmpScr">目标图像</param>
        /// <param name="ptStart">指定点</param>
        /// <param name="clr">指定颜色</param>
        /// <returns>是否连通</returns>
        public static bool GetLUPoint(Bitmap bmpScr, Point ptStart, Color clr) {
            if (0 > ptStart.X - 1 || 0 > ptStart.Y - 1) return false;
            return bmpScr.GetPixel(ptStart.X - 1, ptStart.Y - 1).ToArgb() == clr.ToArgb();
        }

        #endregion

        /// <summary>
        /// 获取rgb平局值
        /// </summary>
        /// <param name="b">b</param>
        /// <param name="g">g</param>
        /// <param name="r">r</param>
        /// <returns>平均值</returns>
        public static byte GetAvg(byte b, byte g, byte r) {
            return (byte)((r   g   b) / 3);
        }
    }
}

标签: 验证码 验证 解析

实例下载地址

c# 验证码解析识别 示例代码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警