调用自定义类实现验证码的生成

这个方法是我同事写的,我觉的相当不错,所以贴出来和大家分享。

验证码生成页面ValidateCode.aspx文件内容如下:

 <%@ Page Language="C#" AutoEventWireup="true" Inherits="ValidateCode" %>

自定义类ValidateCode.cs内容如下:

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ValidateCode : System.Web.UI.Page{

    public static string CodeString{

        get{
            return HttpContext.Current.Session["validatecode"].ToString();
        }
        set{
            HttpContext.Current.Session["validatecode"] = value;
        }
    }

    // 验证码长度
    private int codeLen = 5;
    // 图片清晰度
    private int fineness = 90;
    // 图片宽度
    private int imgWidth = 100;
    // 图片高度
    private int imgHeight = 20;
    // 字体家族名称
    private string fontFamily = "宋体";
    // 字体大小
    private int fontSize = 14;
    // 字体样式
    private int fontStyle = 1;
    // 绘制起始坐标 X
    private int posX = 0;
    // 绘制起始坐标 Y
    private int posY = 0;

    //------------------------------------------------------------
    // ValidateCode.aspx 页面加载函数
    //------------------------------------------------------------
    protected void Page_Load(object sender, EventArgs e){

        #region 读取 Request 传递参数
        // 获取代码长度设置
        if (Request["CodeLen"] != null)
        {
            try
            {
                codeLen = Int32.Parse(Request["CodeLen"]);

                // 规定验证码长度
                if (codeLen < 4 || codeLen > 16)
                    throw new Exception("验证码长度必须在4到16之间");
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 获取图片清晰度设置
        if (Request["Fineness"] != null)
        {
            try
            {
                fineness = Int32.Parse(Request["Fineness"]);

                // 验证清晰度
                if (fineness < 0 || fineness > 100)
                    throw new Exception("图片清晰度必须在0到100之间");
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 获取图片宽度
        if (Request["ImgWidth"] != null)
        {
            try
            {
                imgWidth = Int32.Parse(Request["ImgWidth"]);

                if (imgWidth < 16 || imgWidth > 480)
                    throw new Exception("图片宽度必须在16到480之间");
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 获取图片高度
        if (Request["ImgHeight"] != null)
        {
            try
            {
                imgWidth = Int32.Parse(Request["ImgHeight"]);

                if (imgWidth < 16 || imgWidth > 320)
                    throw new Exception("图片高度必须在16到320之间");
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 获取验证码字体家族名称
        if (Request["FontFamily"] != null)
        {
            fontFamily = Request["FontFamily"];
        }

        // 获取验证码字体大小
        if (Request["FontSize"] != null)
        {
            try
            {
                fontSize = Int32.Parse(Request["FontSize"]);

                if (fontSize < 8 || fontSize > 72)
                    throw new Exception("字体大小必须在8到72之间");
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 获取字体样式
        if (Request["FontStyle"] != null)
        {
            try
            {
                fontStyle = Int32.Parse(Request["FontStyle"]);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 验证码绘制起始位置 X
        if (Request["PosX"] != null)
        {
            try
            {
                posX = Int32.Parse(Request["PosX"]);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        // 验证码绘制起始位置 Y
        if (Request["PosY"] != null)
        {
            try
            {
                posY = Int32.Parse(Request["PosY"]);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
        #endregion

        string validateCode = CreateValidateCode();

        // 生成BITMAP图像
        Bitmap bitmap = new Bitmap(imgWidth, imgHeight);

        // 给图像设置干扰
        DisturbBitmap(bitmap);

        // 绘制验证码图像
        DrawValidateCode(bitmap, validateCode);

        // 保存验证码图像,等待输出
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);

        //Response.ClearContent();
        Response.ContentType = "image/gif";

        Response.End();
    }

    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion

    //------------------------------------------------------------
    // 随机生成验证码,并保存到SESSION中
    //------------------------------------------------------------
    private string CreateValidateCode()
    {
        string validateCode = "";

        // 随机数对象
        Random random = new Random();

        for (int i = 0; i < codeLen; i++)
        {
            // 26: a - z
            int n = random.Next(26);

            // 将数字转换成大写字母
            validateCode += (char)(n + 65);
        }

        // 保存验证码
        Session["ValidateCode"] = validateCode;

        return validateCode;
    }

    //------------------------------------------------------------
    // 为图片设置干扰点
    //------------------------------------------------------------
    private void DisturbBitmap(Bitmap bitmap)
    {
        // 通过随机数生成
        Random random = new Random();

        for (int i = 0; i < bitmap.Width; i++)
        {
            for (int j = 0; j < bitmap.Height; j++)
            {
                if (random.Next(100) <= this.fineness)
                    bitmap.SetPixel(i, j, Color.White);
            }
        }
    }

    //------------------------------------------------------------
    // 绘制验证码图片
    //------------------------------------------------------------
    private void DrawValidateCode(Bitmap bitmap, string validateCode)
    {
        // 获取绘制器对象
        Graphics g = Graphics.FromImage(bitmap);

        // 设置绘制字体
        Font font = new Font(fontFamily, fontSize, GetFontStyle());

        // 绘制验证码图像

        char[] chars = validateCode.ToCharArray();

        for( int i=0;i<chars.Length;i++ )
            g.DrawString(chars[i].ToString(),font,Brushes.Black, posX+(i*(fontSize+5)), posY);
    }

    //------------------------------------------------------------
    // 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
    //------------------------------------------------------------
    private FontStyle GetFontStyle()
    {
        if (fontStyle == 1)
            return FontStyle.Bold;
        else if (fontStyle == 2)
            return FontStyle.Italic;
        else if (fontStyle == 3)
            return FontStyle.Bold | FontStyle.Italic;
        else
            return FontStyle.Regular;
    }

}

执行ValidateCode.aspx文件,页面就会生成验证码,效果相当不错哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值