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

生成验证码

2013年01月24日 ⁄ 综合 ⁄ 共 1632字 ⁄ 字号 评论关闭

using System;
using System.Web;
using System.Drawing;

/// <summary>
/// Summary description for CheckCode
/// </summary>
public class CheckCode:System.Web.IHttpHandler
{
 public CheckCode()
 {
  //
  // TODO: Add constructor logic here
  //
 }

    #region IHttpHandler 成员

    bool IHttpHandler.IsReusable
    {
        get { return false; }
    }

    void IHttpHandler.ProcessRequest(HttpContext context)
    {
        string allChar = "0123456789ABCDEFGHIJKLMNOPQRSTUWXYZ";
        int len = allChar.Length;
        int i = 0;
        string res = "";
        System.Random ra = new Random();
        int next = -1;
        string pc = "";
        do
        {
            next = ra.Next(0, len - 1);
            pc = allChar.Substring(next, 1);
            if (res.IndexOf(pc) == -1)
            {
                i++;
                res += pc;
            }

        } while (i < 6);

        using (System.Drawing.Image image = new System.Drawing.Bitmap(100, 25))
        {

            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("Arial", 14, System.Drawing.FontStyle.Regular);
            Brush b = System.Drawing.Brushes.Black;
            g.Clear(Color.FromArgb(255, 255, 255));
            g.DrawString(res, f, b, 2, 2);
            //g.Clear(System.Drawing.Color.White);
            Pen blackPen = new Pen(Color.Black, 0);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ClearContent();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            context.Response.End();
            g.Dispose();
            image.Dispose();
            context.Session["CheckCode"] = res;
        }
    }

    #endregion
}

抱歉!评论已关闭.