现在的位置: 首页 > 综合 > 正文

验证码代码

2013年11月26日 ⁄ 综合 ⁄ 共 1274字 ⁄ 字号 评论关闭

protected void Page_Load(object sender, EventArgs e)

    {

        string str = "0123456789";

        char[] chs = str.ToCharArray();

        Random rand = new Random();

        string validater = "";

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

        {

            char x = chs[rand.Next(0, chs.Length)];

            validater += x;

        }

        Session["validater_code"] = validater;

        //Response.Write(validater);

        CreateImage(validater);

    }

    protected void CreateImage(string str)

    {

        int iWidth = str.Length * 11;

        Bitmap img = new Bitmap(iWidth,20);

        Graphics g = Graphics.FromImage(img);

        g.Clear(Color.White);

        Color[] colors = new Color[] {Color.White,Color.Red,Color.Yellow,Color.Black,Color.Blue};

        Random rand = new Random();

        for (int i = 0; i < str.Length; i++)

        {

            Color c=colors[rand.Next(0,colors.Length)];

            Font f = new Font("Courier New",11);

            Brush b = new System.Drawing.SolidBrush(c);

            g.DrawString(str.Substring(i, 1), f, b, (i * 10) + 1, 1, StringFormat.GenericDefault);

 

        }

       //描边

        g.DrawRectangle(new Pen(Color.Black), 0, 0, img.Width - 1, img.Height - 1); ;

        //保存图片到内存

        MemoryStream ms = new MemoryStream();

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

        //页面的东西全部清除 只剩下面的图片

        Response.Clear();

        Response.ContentType = "image/Jpeg";

        Response.BinaryWrite(ms.ToArray());

        g.Dispose();

        img.Dispose();

 

    }

【上篇】
【下篇】

抱歉!评论已关闭.