C#手写验证码

一、随机生成验证码数据(两种方法)
1.简单实用


private string RandCode(int len)<br>
        {
            string str = Guid.NewGuid().ToString();<br>
            return str.Substring(str.Length - len);<br>
        }

2.机动性高,扩展性足

private string RandCode(int len)
        {
            string words = "1234567890" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz";
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < len; i++)
            {
                int index = random.Next(0, words.Length);<br>
                char c = words[index];
                if (sb.ToString().Contains(c))
                {
                    i--;
                    continue;
                }
                sb.Append(words[index] + "");
            }
            return sb.ToString();
        }

二、随机生成颜色

private Color RandColor()
        {
            Random random = new Random();
            int red = random.Next(10, 240);
            int green = random.Next(10, 240);
            int blue = random.Next(10, 240);
            return Color.FromArgb(red, green, blue);
        }

三、实用Drawing类绘制图片,注意实用TempData暂存验证码数据

public ActionResult ValidateCode()
        {
            byte[] data = null;
            string code = RandCode(5);
            TempData["code"] = code;
            //画板
            Bitmap imgCode = new Bitmap(85, 35);
            //画笔
            Graphics gp = Graphics.FromImage(imgCode);
            gp.DrawString(code, new Font("宋体", 14), Brushes.White, new PointF(15, 8));
            Random random = new Random();
            //画噪线
            for (int i = 0; i < 5; i++)
            {
                gp.DrawLine(new Pen(RandColor()), random.Next(imgCode.Width), random.Next(imgCode.Height), random.Next(imgCode.Width), random.Next(imgCode.Height));
            }
            //画噪点
            for (int i = 0; i < 50; i++)
            {
                //指定像素的颜色来画噪点
                imgCode.SetPixel(random.Next(imgCode.Width), random.Next(imgCode.Height), RandColor());
            }
            gp.Dispose();
            //创建内存流
            MemoryStream ms = new MemoryStream();
            imgCode.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            data = ms.GetBuffer();
            return File(data, "image/jpeg");
        }
posted @ 2022-04-05 20:32  小堂子  阅读(23)  评论(0)    收藏  举报