生成验证码及其使用

一、生成验证码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Drawing;
using System.Web.SessionState;     //第一步:导入此命名空间

//生成验证码
namespace Glasses.Base
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GeneralCode : IHttpHandler, IRequiresSessionState //第二步:实现接口   到此就可以像平时一样用Session了
    {
        public void ProcessRequest(HttpContext context)
        {
            //string a = context.Request["a"].ToString();
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Write("");
            //特别注意,如不加,单击验证图片’看不清换一张’,无效果.
            CreateCheckCodeImage(GenerateCheckCode(context), context);
        }

        private string GenerateCheckCode(HttpContext context)
        {
            string YanZheng = "";
            Random ran = new Random();
            for (int i = 0; i < 4; i++)
            {
                int num = ran.Next(1, 62);
                if (num >= 1 && num <= 10)
                {
                    //48-57=>1-10
                    char temp = (char)(num + 47);
                    YanZheng += temp.ToString();
                }
                else if (num >= 11 && num <= 36)
                {
                    //65-90=>11-36
                    char temp = (char)(num + 54);
                    YanZheng += temp.ToString();
                }
                else if (num >= 37 && num <= 62)
                {
                    //97-122=>37-62
                    char temp = (char)(num + 60);
                    YanZheng += temp.ToString();
                }
            }
            context.Session["jiaoyan"] = YanZheng;
            return YanZheng;
        }

        private void CreateCheckCodeImage(string checkCode, HttpContext context)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            System.Drawing.Bitmap image = new
                System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.5)), 25);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);
                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.ClearContent();
                context.Response.ContentType = "image/Gif";
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }

        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
二、使用

<script type="text/javascript">
                        function changeCode() {
                            var r = Math.random();
                            var codeImage = document.getElementById("codeImage");
                            codeImage.src = "/Base/GeneralCode.ashx?r="+r;
                        }
                    </script>
                    <img src="/Base/GeneralCode.ashx" width="60px" id="codeImage" 
                      onclick="changeCode();" title="看不清楚点击换一张"/>

posted on 2011-07-03 11:46  windfree  阅读(220)  评论(0编辑  收藏  举报