利用GDI+在Winfrom绘制验证码

2018-04-18 10:40:47 浏览数 (1)

代码语言:javascript复制
            string yzm;  
private void yangzhengma()
        {
            Bitmap bt = new Bitmap(70,22);//创建位图对象
            Graphics gs = Graphics.FromImage(bt);//在该位图上进行绘制
            Random rd = new Random();
            yzm="";
            for (int i = 0; i < 5; i  )
            {   yzm =rd.next(0,10);
                string[] frons = { "微软雅黑","宋体","黑体","仿宋","隶书"};//创建字体数组
                Color[] color = { Color.Black, Color.Yellow, Color.Red, Color.Green, Color.Blue };
                gs.DrawString(yzm[i].ToString(),new Font(frons[rd.Next(0,5)],12,FontStyle.Bold),new SolidBrush(color[rd.Next(0,5)]),i*12,5);
            }
            for (int i = 0; i < 10; i  )//绘制验证码中的直线
            {
                Point pt1 = new Point(rd.Next(0,70),rd.Next(0,20));
                Point pt2 = new Point(rd.Next(0, 70), rd.Next(0, 20));
                Pen pen = new Pen(Color.Green);
                gs.DrawLine(pen,pt1,pt2);
            }
            for (int i = 0; i < 100; i  )绘制验证中的白点
            {
               
                bt.SetPixel(rd.Next(0, 70), rd.Next(0, 20), Color.Black);
            }
            toolStripLabel5.BackgroundImage = bt;
            
        }

程序最后只需要讲输入的字符串与string   yzm进行比较即可。设计的最终效果如图:

0 人点赞