标签:
网站登录总是会用到验证码,生成验证码对于C#来说很简单,我用的是一般处理程序来写的验证码。具体代码如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
namespace UI.ajax
{
    /// <summary>
    /// code 的摘要说明
    /// </summary>
    public class code : IHttpHandler
    {
        /// <summary>
        /// 验证码类型(0-字母数字混合,1-数字,2-字母)
        /// </summary>
        private string validateCodeType = "0";
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.BufferOutput = true;
            context.Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.AppendHeader("Pragma", "No-Cache");
            string ValidateCode = GenerateCheckCode();
//context.Session["CheckCode"] = ValidateCode;//将字符串保存到Session中,以便需要时进行验证
            CreateCheckCodeImage(context, ValidateCode);
        }
        public void CreateCheckCodeImage(HttpContext context, string checkCode)
        {
            int randAngle = 40; //随机转动角度
            int mapwidth = (int)(checkCode.Length * 18);
            Bitmap map = new Bitmap(mapwidth, 24);//创建图片背景
            Graphics graph = Graphics.FromImage(map);
            graph.Clear(Color.White);//清除画面,填充背景
            graph.DrawRectangle(new Pen(Color.LightGray, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
Random rand = new Random();
            //验证码旋转,防止机器识别
            char[] chars = checkCode.ToCharArray();//拆散字符串成单字符数组
            //文字距中
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };
            //画图片的背景噪音线
            for (int i = 0; i < 2; i++)
            {
                int x1 = rand.Next(10);
                int x2 = rand.Next(map.Width - 10, map.Width);
                int y1 = rand.Next(map.Height);
                int y2 = rand.Next(map.Height);
                graph.DrawLine(new Pen(c[rand.Next(7)]), x1, y1, x2, y2);
            }
            for (int i = 0; i < chars.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(5);
                Font f = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Regular);//字体样式(参数2为字体大小)
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                Point dot = new Point(12, 16);
                float angle = rand.Next(-randAngle, randAngle);//转动的度数
                graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
                graph.RotateTransform(angle);
                graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);
                graph.RotateTransform(-angle);//转回去
                graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
            }
            //生成图片
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/gif";
            context.Response.BinaryWrite(ms.ToArray());
            graph.Dispose();
            map.Dispose();
        }
        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;
            System.Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                number = random.Next();
                code = (char)(‘0‘ + (char)(number % 10));
                if (number % 2 == 0)
                    code = (char)(‘0‘ + (char)(number % 10));
                else
                    code = (char)(‘A‘ + (char)(number % 26));
                //去掉0,O,I,o,i,Z,z
                if (code.ToString() == "O" || code.ToString() == "I" || code.ToString() == "o" || code.ToString() == "i" || code.ToString() == "Z" || code.ToString() == "z")
                {
                    i--;
                    continue;
                }
                //要求全为数字
                if (validateCodeType == "1")
                {
                    if ((int)code < 48 || (int)code > 57)
                    {
                        i--;
                        continue;
                    }
                }
                //要求全为字母
                if (validateCodeType == "2")
                {
                    if ((int)code > 47 || (int)code < 58)
                    {
                        i--;
                        continue;
                    }
                }
                checkCode += code.ToString();
            }
            return checkCode;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
具体效果为:

标签:
原文地址:http://www.cnblogs.com/0208wky/p/4738700.html