生成验证码代码

来源:互联网 发布:搞怪视频软件 编辑:程序博客网 时间:2024/06/06 03:12
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Drawing.Imaging;using System.Drawing.Drawing2D;using System.Drawing;using System.IO;namespace JXC.Admin.inc{    /// <summary>    /// 产生一个4位的验证码    /// </summary>    public partial class verifycode : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            string check_code = this.CreateStr();            this.CreateCode(check_code);            Session["check_code"] = check_code;        }        protected string CreateStr()        {            string str = string.Empty;            Random random = new Random();            str = random.Next(1000,9999).ToString();            return str;        }        /// <summary>        /// 用于美化验证码        /// </summary>        /// <param name="code"></param>        protected void CreateCode(string code)        {            if (code.Length == 0)            {                return;            }            Random random = new Random();            Bitmap map = new Bitmap(4 * 14, 30);//创建一个位图 (宽度为4*14 高度为30 像素)            Graphics g = Graphics.FromImage(map);//完成绘图            g.Clear(Color.White);//清空图片内容并设置背景色为白色            g.DrawRectangle(new Pen(Color.Gray), 0, 0, map.Width -1, map.Height -1);//用灰色的画笔在map上画一个矩形            //开始写字            Matrix matrix; //声明用来操作矩阵的类            LinearGradientBrush brush = new LinearGradientBrush(new Point(0,0),new Point(map.Width,map.Height),Color.Red,Color.Green);            for (int i = 0; i < code.Length; i++)            {                string schar = code.Substring(i,1);                matrix = g.Transform;//获取当前绘图的世界坐标系                float shearx = 0.0F;                float sheary = 0.0F;                matrix.Shear(shearx, sheary);                g.Transform = matrix;                g.DrawString(schar,new Font("黑体",14.0f,FontStyle.Bold),brush,new PointF(0.0f+(13.0f*i),random.Next(30-20)));            }            //画10条干扰线            for (int i = 0; i < 10; i++)            {                int x1 = random.Next(map.Width);                int y1 = random.Next(map.Height);                int x2 = random.Next(map.Width);                int y2 = random.Next(map.Height);                g.DrawLine(new Pen(Color.Black), new Point(x1, y1), new Point(x2, y2));             }            //画20个干扰点            for (int i = 0; i < 20; i++)            {                map.SetPixel(random.Next(map.Width),random.Next(map.Height),Color.FromArgb(random.Next(255),random.Next(255),random.Next(255)));            }            Response.Clear();            MemoryStream ms = new MemoryStream();            map.Save(ms, ImageFormat.Gif);            Response.ContentType = "image/Gif";            Response.BinaryWrite(ms.ToArray());        }    }}

0 0
原创粉丝点击