VerifyCode.ashx生成验证码的代码

2015-03-03 12:03:07  访问(1802) 赞(0) 踩(0)

<%@ WebHandler Language="C#" Class="VerifyCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState; //用到session

public class VerifyCode : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string strKey = context.Request.QueryString["key"];

        if (strKey == null || strKey.Length == 0)
            strKey = "VerCode";
        else
        {
            strKey = strKey.Trim();

            if (strKey.Length == 0)
                strKey = "VerCode";
        }

        string size = context.Request.QueryString["size"];

        int iSize = 4;

        if (size != null && size.Length > 0)
        {
            iSize = int.Parse(size);
        }

        string verCode = GetVerifyCode(iSize, "");

        context.Session[strKey] = verCode;

        CreateImages(verCode);
    }
     

    /// <summary>
    /// 生成验证码
    /// </summary>
    /// <param name="iSize"></param>
    /// <returns></returns>
    public string GetVerifyCode()
    {
        return GetVerifyCode(0);
    }

    /// <summary>
    /// 生成验证码
    /// </summary>
    /// <param name="iSize"></param>
    /// <returns></returns>
    public string GetVerifyCode(int iSize)
    {
        return GetVerifyCode(iSize, null);
    }

    /// <summary>
    /// 生成验证码
    /// </summary>
    /// <param name="iSize"></param>
    /// <param name="strKey"></param>
    /// <returns></returns>
    public string GetVerifyCode(int iSize, string strKey)
    {

        string Vchar = "1,2,3,4,5,6,7,8,9,0";

        if (strKey != null && strKey.Length > 0)
            Vchar = strKey.Trim();

        int VcodeNum = iSize;

        if (VcodeNum <= 0)
            VcodeNum = 4;

        string[] VcArray = Vchar.Split(',');
        string VNum = ""; //由于字符串很短,就不用StringBuilder了

        int temp = -1; //记录上次随机数值,尽量避免生产几个一样的随机数

        //采用一个简单的算法以保证生成随机数的不同

        Random rand = null;// new Random();

        for (int i = 1; i <= VcodeNum; ++i)
        {

            rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

            int t = rand.Next(VcArray.Length);

            temp = t;

            VNum += VcArray[t];
        }

        return VNum;
    }

    /// <summary>
    /// 生成验证图片
    /// </summary>
    /// <param name="checkCode">验证字符</param>
    public void CreateImages(string checkCode)
    {
        CreateImages(checkCode, null, null);
    }

    /// <summary>
    /// 生成验证图片
    /// </summary>
    /// <param name="checkCode"></param>
    /// <param name="cArray"></param>
    /// <returns></returns>
    public void CreateImages(string checkCode, Color[] cArray)
    {
        CreateImages(checkCode, cArray, null);
    }

    /// <summary>
    /// 生成验证图片
    /// </summary>
    /// <param name="checkCode"></param>
    /// <param name="cArray"></param>
    /// <param name="fontArray"></param>
    /// <returns></returns>
    public void CreateImages(string checkCode, Color[] cArray, string[] fontArray)
    {
        if (checkCode == null || checkCode.Trim().Length == 0)
            return;

        int iwidth = (int)(checkCode.Length * 13);

        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 23);

        System.Drawing.Graphics g = Graphics.FromImage(image);

        g.Clear(Color.White);

        System.Drawing.Color[] c = null;

        if (cArray == null)
            c = new Color[] { Color.Black };
        else if (cArray.Length == 0)
            c = new Color[] { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        else
            c = cArray;

        //定义字体 
        string[] font = null;

        if (fontArray == null || fontArray.Length == 0)
            font = new string[] { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        else
            font = fontArray;

        Random rand = new Random();
        //随机输出噪点
        for (int i = 0; i < 50; i++)
        {
            int x = rand.Next(image.Width);
            int y = rand.Next(image.Height);
            g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
        }

        //输出不同字体和颜色的验证码字符

        for (int i = 0; i < checkCode.Length; i++)
        {
            int cindex = rand.Next(c.Length);
            int findex = rand.Next(font.Length);

            Font f = new System.Drawing.Font(font[findex], 10, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(c[cindex]);
            int ii = 4;
            if ((i + 1) % 2 == 0)
            {
                ii = 2;
            }
            g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * 12), ii);
        }
        //画一个边框

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

        //输出到浏览器
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ContentType = "image/Jpeg";
        HttpContext.Current.Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


上一条:

下一条:


 

相关评论

评论加载中……
 

发表评论

类型:
内容:
  (Alt+Enter)