【笔记】 - C# 后台生成验证码

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;

namespace CAP.Content.js
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GetCaptchaPicture();
        }

        /// <summary>
        /// 
        /// </summary>
        private void GetCaptchaPicture()
        {
            //去掉0和O以防混淆
            string[] codes = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            //生成随即生成器
            Random rand = new Random();

            //生成随机数
            string vCode = "";
            for (int i = 0; i < 6; i++)
            {
                vCode += codes[rand.Next(codes.Length)];
            }

            //验证码存到session
            Session["dyncvcode"] = vCode;

            //开始画图
            using (System.Drawing.Bitmap img = new System.Drawing.Bitmap(90, 34))
            {
                Graphics g = Graphics.FromImage(img);
                g.Clear(Color.White);

                for (int i = 0; i < 10; i++)
                {
                    //画背景线条
                    Pen p = new Pen(Color.FromArgb(rand.Next()));
                    var x1 = rand.Next(100);
                    var x2 = rand.Next(30);
                    var y1 = rand.Next(30);
                    var y2 = rand.Next(30);
                    g.DrawLine(p, x1, x2, y1, y2);
                }

                //画文字
                g.DrawString(vCode, new Font("Consolas", 16f, FontStyle.Italic), Brushes.Black, 5, 5);

                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = rand.Next(img.Width);
                    int y = rand.Next(img.Height);
                    img.SetPixel(x, y, Color.FromArgb(rand.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);

                Response.ClearContent();
                Response.ContentType = "image/jpeg";
                img.Save(Response.OutputStream, ImageFormat.Jpeg);
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值