验证码编写

来源:互联网 发布:死神的精确度 知乎 编辑:程序博客网 时间:2024/05/22 03:13
 

在用到验证码界面加入Image控件,控件的ImageUrl属性等于写验证码的界面,如:

创建个页面——yz.aspx,用来写验证码。那么ImageUrl=” yz.aspx”。

验证码的界面的代码为(非本人代码,这代码是老师上课写的):

protected void Page_Load(object sender, EventArgs e)

    {

        System.Drawing.Image img = new Bitmap(150,30);

        Graphics g = Graphics.FromImage(img);

        this.DealImage(img, 1500);

        g.DrawLine(Pens.Red, 0, 0, 150, 30);

        string code = this.GenerateCode();

        Font font = new Font("宋体", 24, FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout);

        g.DrawString(code, font, Brushes.GreenYellow,5, 2);

        this.Response.Clear();

        MemoryStream ms = new MemoryStream();

        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        this.Response.BinaryWrite(ms.ToArray());

        this.Response.Flush();

        this.Response.End();

    }

    private void DealImage(System.Drawing.Image img, int nums)

    {

        Bitmap b = img as Bitmap;

        Random ran = new Random();

        for (int i = 0; i < nums; i++)

        {

            b.SetPixel(ran.Next(0, img.Width), ran.Next(0, img.Height), Color.White);

        }

    }

    private string GenerateCode()

    {

        Random ran = new Random(DateTime.Now.Millisecond);

        StringBuilder sb = new StringBuilder(6);

        for (int i = 0; i < 6; i++)

        {

            sb.Append(ran.Next(0, 9));

        }

        Session["sb"] = sb.ToString();

        return sb.ToString();

    }

 

原创粉丝点击