zoukankan      html  css  js  c++  java
  • 生成图片验证码

     /// <summary>
            /// 图片验证码
            /// </summary>
            /// <returns></returns>
            public ActionResult ValidateCode()
            {
                byte[] data = null;
                string code = RandCode(5);
                TempData["code"] = code;
                //画板
                Bitmap imgCode = new Bitmap(80, 25);
                //画笔
                Graphics gp = Graphics.FromImage(imgCode);
                //背景为白色
                gp.FillRectangle(Brushes.White, 0, 0, imgCode.Width, imgCode.Height);
                gp.DrawString(code, new Font("宋体", 14), Brushes.Black, new PointF(10, 2));
                Random rand = new Random();
                //绘制燥线
                for (int i = 0; i < 5; i++)
                {
                    gp.DrawLine(new Pen(RandColor()), rand.Next(imgCode.Width), rand.Next(imgCode.Height), rand.Next(imgCode.Width), rand.Next(imgCode.Height));
                }
                //绘制噪点
                for (int i = 0; i < 50; i++)
                {
                    imgCode.SetPixel(rand.Next(imgCode.Width), rand.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/jepg");
            }
            /// <summary>
            /// 生成随机数
            /// </summary>
            /// <param name="len"></param>
            /// <returns></returns>
            private string RandCode(int len)
            {
                StringBuilder sb = new StringBuilder();
                string words = "0987654321qwerghjzxcvb";
                Random random = new Random();
                for (int i = 0; i < len; i++)
                {
                    char ch = words[random.Next(0, words.Length)];
                    if (sb.ToString().Contains(ch))
                    {
                        i--;
                        continue;
                    }
                    sb.Append(ch + "");
                }
                return sb.ToString();
            }
    
            private Color RandColor()
            {
                Random random = new Random();
                int red = random.Next(10, 200);
                int green = random.Next(10, 200);
                int blue = random.Next(10, 200);
                return Color.FromArgb(red, green, blue);
            }
  • 相关阅读:
    pip升级报错AttributeError: 'NoneType' object has no attribute 'bytes'
    在Windows中安装MySQL
    nginx配置成功,浏览器无法访问
    mysql 安装完以后没有mysql服务
    对字符串的切片操作
    linux下anaconda的安装和使用
    python学习笔记
    python学习笔记2018-9-18
    python学习笔记2018-9-17
    电脑必须用U盘引导盘才能进系统解决办法
  • 原文地址:https://www.cnblogs.com/baixiaoguang/p/7094708.html
Copyright © 2011-2022 走看看