asp.net 验证码 【Drawing.BitMap】

新建一个解决方案管理器---》添加--》新建网站---》asp.net空网站 。

在里面添加两个页(一个请求页面(Default.aspx),一个处理页面(VerifyCode.aspx))

 

 请求页代码Default.aspx.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        string txt = TxtCerifyCode.Text;
        string vtxt = Session["code"].ToString();
        string msg = "";

        if (txt == vtxt)  //如果你在txt(也就是TextBox1.Text)填入的值与在服务器端取到是值一致
        {
            msg = "验证码输入正确";
        }
        else
        {
            msg = "验证码错误";
        }

        ClientScript.RegisterClientScriptBlock(this.GetType(), "script0", "<script>alert('" + msg + "');</script>");
    }
}

 

 Default.aspx源代码

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        var refreshCode = function () {
            document.getElementById('ImgVerifyCode').src = "VerifyCode.aspx";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:TextBox runat="server" ID="TxtCerifyCode" />
        <asp:Image ID="ImgVerifyCode" src="VerifyCode.aspx" runat="server" /> 
        <a href="javascript:refreshCode()">刷新验证码</a>

        <br /><br />

        <asp:Button runat="server" ID="BtnSubmit" Text="提交" onclick="BtnSubmit_Click" />
         
    </div>
    </form>
</body>
</html>


 

 处理页代码 VerifyCode.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Collections; 
using System.ComponentModel; 
using System.Data; 
using System.Web.SessionState; 
using System.Web.UI.HtmlControls; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Drawing.Text;

//这个页面仅仅是生成一副图片,并处理了这幅图片而已。

public partial class VerifyCode : System.Web.UI.Page
{
    //定义一个字体数组
    static string[] FontItems = new string[] 
    {
        "Arial", 
        "Helvetica", 
        "Geneva", 
        "sans-serif", 
        "Verdana" 
    };
    //定义一个画笔数组。
    static Brush[] BrushItems = new Brush[]
    { 
        Brushes.OliveDrab, 
        Brushes.ForestGreen, 
        Brushes.DarkCyan, 
        Brushes.LightSlateGray, 
        Brushes.RoyalBlue, 
        Brushes.SlateBlue, 
        Brushes.DarkViolet, 
        Brushes.MediumVioletRed, 
        Brushes.IndianRed, 
        Brushes.Firebrick, 
        Brushes.Chocolate, 
        Brushes.Peru, 
        Brushes.Goldenrod 
     };
    //定义一个颜色数组
    static string[] BrushName = new string[] 
    {   "OliveDrab", 
        "ForestGreen", 
        "DarkCyan", 
        "LightSlateGray", 
        "RoyalBlue", 
        "SlateBlue", 
        "DarkViolet", 
        "MediumVioletRed", 
        "IndianRed", 
        "Firebrick", 
        "Chocolate", 
        "Peru", 
        "Goldenrod" 
    };
    private static Color BackColor = Color.White;
    private static Pen BorderColor = Pens.DarkGray;
    private static int Width = 52;   //图片的宽度
    private static int Height = 21;  //图片的高度
    private Random _random;
    private string _code;
    private int _brushNameIndex;

    override protected void OnInit(EventArgs e)
    {
        // 
        // CODEGEN: This call is required by the ASP.NET Web Form Designer. 
        // 
        //InitializeComponent(); 
        //base.OnInit(e); 
    }

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    private void InitializeComponent()
    {
        //this.Load += new System.EventHandler(this.Page_Load); 
    }

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    public void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            // 
            // TODO : initialize 
            // 
            this._random = new Random();
            this._code = GetRandomCode(); //取得一个 4 位的随机码
            // 
            // TODO : use Session["code"] save the VerifyCode 
            // 
            Session["code"] = this._code;  //将随机取得的 4 位的随机码添加到Session里面去 ,于是在请求页面(Default.aspx.cs)取得这个Sesssion的值就行了
            // 
            // TODO : output Image 
            // 
            this.SetPageNoCache();  //设置页面不被缓存
            this.OnPaint();   //绘画事件
        }
    }

    /// <summary> 
    /// 设置页面不被缓存 
    /// </summary> 
    private void SetPageNoCache()
    {
        Response.Buffer = true;
        Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
        Response.Expires = 0;
        Response.CacheControl = "no-cache";
        Response.AppendHeader("Pragma", "No-Cache");
    }

    /// <summary> 
    /// 取得一个 4 位的随机码 
    /// </summary> 
    /// <returns></returns> 
    private string GetRandomCode()
    {
        return Guid.NewGuid().ToString().Substring(0, 4);
    }

    /// <summary> 
    /// 随机取一个字体 
    /// </summary> 
    /// <returns></returns> 
    private Font GetFont()
    {
        int fontIndex = _random.Next(0, FontItems.Length);
        FontStyle fontStyle = GetFontStyle(_random.Next(0, 2));
        return new Font(FontItems[fontIndex], 12, fontStyle);
    }

    /// <summary> 
    /// 取一个字体的样式 
    /// </summary> 
    /// <param name="index"></param> 
    /// <returns></returns> 
    private FontStyle GetFontStyle(int index)
    {
        switch (index)
        {
            case 0:
                return FontStyle.Bold;
            case 1:
                return FontStyle.Italic;
            default:
                return FontStyle.Regular;
        }
    }

    /// <summary> 
    /// 随机取一个笔刷 
    /// </summary> 
    /// <returns></returns> 
    private Brush GetBrush()
    {
        int brushIndex = _random.Next(0, BrushItems.Length);
        _brushNameIndex = brushIndex;
        return BrushItems[brushIndex];
    }

    /// <summary> 
    /// 绘画事件 
    /// </summary> 
    private void OnPaint()
    {
        Bitmap objBitmap = null;
        Graphics g = null;
        try
        {
            objBitmap = new Bitmap(Width, Height);
            g = Graphics.FromImage(objBitmap);
            Paint_Background(g);
            Paint_Text(g);
            Paint_TextStain(objBitmap);
            Paint_Border(g);
            objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
            Response.ContentType = "image/gif";
        }
        catch { }
        finally
        {
            if (null != objBitmap)
                objBitmap.Dispose();
            if (null != g)
                g.Dispose();
        }
    }

    /// <summary> 
    /// 绘画背景颜色 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Background(Graphics g)
    {
        g.Clear(BackColor); //清除绘图并以指定背景色填充
        
    }

    /// <summary> 
    /// 绘画边框 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Border(Graphics g)
    {
        g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
    }

    /// <summary> 
    /// 绘画文字 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Text(Graphics g)
    {
        g.DrawString(_code, GetFont(), GetBrush(), 3, 1);
    }

    /// <summary> 
    /// 绘画文字噪音点 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_TextStain(Bitmap b)
    {
        for (int n = 0; n < 30; n++)
        {
            int x = _random.Next(Width);
            int y = _random.Next(Height);
            b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));
        }
    }
}


 

你可能感兴趣的:(验证码)