MVC第三波书店存书店验证码

 #region 验证码
        public FileResult CreateCode()
        {
            return File(CreateCodeImg(), "image/jpeg");
        }
        public byte[] CreateCodeImg()
        {
            //字体颜色
            Color[] color = { Color.Red, Color.Black, Color.Blue, Color.Green };
            //字体类型
            string[] font = { "黑体", "隶书", "幼圆" };
            //创建图片对象
            Bitmap image = new Bitmap(120, 50);
            //创建画板
            Graphics g = Graphics.FromImage(image);
            //使用白色清空画板
            g.Clear(Color.White);
            try
            {
                //创建随机生成器
                Random random = new Random();
                //绘制线
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int x2 = random.Next(image.Width);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(color[random.Next(color.Length)]), x1, y1, x2, y2);
                }
                //绘制干扰点
                for (int i = 0; i < 20; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, color[random.Next(color.Length)]);
                }
                string validateCode = Guid.NewGuid().ToString().Replace("-", "").Substring(2, 4);

                TempData["code"] = validateCode;
                //绘制字符
                for (int i = 0; i < validateCode.Length; i++)
                {
                    g.DrawString(validateCode[i].ToString(),
                        new Font(font[random.Next(font.Length)], 20),
                        new SolidBrush(color[random.Next(color.Length)]),
                        i * 20, 5);
                }
                //绘制边框
                g.DrawRectangle(new Pen(Color.Gray), -1, -1, image.Width + 1, image.Height + 1);

                //保存图片
                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_74456535

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值